I heard it was better to put the Javascript in an external file and call it from the html file. However, I tested some code and it does not work when it is an external file, although it does work fine when it is inline in the html file.
Here is the code:
var bigImage = document.getElementById(‘zoom’);
var smImage = document.getElementById(‘thumbnail’);
Most likely, the problem is that you are including your js file in a head tag or somewhere above your main content. By doing this, you are executing your js code before full html content has been attached. As a result, when your js code executes, it does not recognize any html element because there isn’t any. Try including them at the end of your html content or use onload functionality.
You should be able to add the js file in a script tag. The page loads first then JavaScript. You need conditionals to load an external script if the JavaScript file is in the head tag.
<html>
<head>
</head>
<body>
// your current code
<script src="your file"></script>
</body>
</html>
Thank you, it makes sense. But what if I cannot move the link to the js file from the head tag? Is there any way I can edit the external script itself so that it is executed AFTER the html page is loaded?
The issue with vanilla JavaScript is compatibility issues across browsers. Here is a stack overflow article with vanilla JavaScript code that works similar to jQuery function. Look at the first response in the article.
Last option if you don’t care if it works in all browsers is DomContentLoaded. Look at the “Browser compatibility” sub-heading to see which browsers are compatible. There is example code under the “Example” sub-heading. You will need to place all your code inside the the callback.