Need help with JS Javascript copied into parent page

I am having an issue with some JavaScript copied from FabricJS. All the code works well when it’s in a page of it’s own ie no Wappler coding.

I have now copied the html to an SPA page and put all the script into the parent page. When I run the site I get an error, even before I have got to the SPA page with the relevant html on it.

My understanding of the error is that the JavaScript loads when the site first loads, and it looks for “getElementById(‘vehicles’)” but can’t find it because the relevant html has not yet loaded, and therefore results in the error.

OK, I understand the error, but what I don’t understand is how to change my script so that it only runs when the select menu is changed (ie after the whole page is loaded)?

I am not fluent in JavaScript and I have done the usual Googling but without any success.

The offending JavaScript is

// To allow change of vehicle
document.getElementById('vehicles').onchange = function() {  //  << the error occurs on this line
   canvas.setBackgroundImage('', canvas.renderAll.bind(canvas));  // Clear the current vehicle
   loadBackground(fileDir + this.value);
};

and I get the following error

Uncaught TypeError: Cannot set property 'onchange' of null

and the Form Select Menu is

<div style="display: inline-block">
	<p>Change the vehicle:
		<select id="vehicles" class="custom-select" name="vehs">
			<option value="01-5_Door_Hatch.svg" selected>5 Door Hatchback</option>
			<option value="02-3_Door_Hatch.svg">3 Door Hatchback</option>
			<option value="03-4_Door_Saloon.svg">4 Door Saloon</option>
			<option value="04-Estate.svg">Estate 5 Door</option>
			<option value="05-MPV.svg">MPV</option>
		</select>
	</p>
</div>

My saving grace is that I can put this all back into a single html page and run this function there. I really don’t want to do that, I want it to look and feel like the rest of the site.

I am sure it is a simple fix, can somebody help?

Community Page
Last updated: