call js function from html
This is a simple one that I use quite often: I make a call to a JS function from within the HTML document. This function is called as soon as the DOM is ready. It sets the onload property for the element.
I think you’d be surprised how much time you can save trying to get the onload property to work correctly the first time. It’s really important to make sure you’re setting the right onload value. For instance, if you’re loading a HTML document from a remote server, the onload property is usually set to null, which means that the element doesn’t actually load until after the DOM has been loaded.
I found the first few times I made this mistake, the page would just hang after I clicked the “Enter” button. The reason for this is that my browsers default window.onload property is onload=”close”, which means that you can only set a function to close the window when the DOM is ready and the loading was finished.
You can fix this by setting window.onload to the function you want to call, like window.onload = myFunction;. This way, you can only call the function once the DOM is loaded.
The script is not meant to be included in the HTML that’s loaded. It’s just meant to be added to the DOM.
For the sake of the page having a working function, you need to add that function somewhere, so it can be used by the page content. To accomplish that, either put it at the end of the HTML tags, or put it in the head.
I understand the need to do things like display.html and display.html.
It’s not really a big deal, but I have a feeling that a lot of people are gonna be very confused when they see the difference. In the end, the function is added to the DOM and can be called from the code via document.getElementById.