noobdesigner Posted May 20, 2020 Share Posted May 20, 2020 (edited) Hello, first of all, sorry for the extremly nooby quastion and my not so good English, but this makes me insane. My HTML Code --> index.html: <html> <head> <script src="main.js"></script> </head> <body> <input id="btn" type="button" value="Button"> </body> </html> And my JavaScript Code --> main.js: function test() { alert("Test"); } btn.addEventListener ("click", test); It is written everywhere, that the <script src="xyz"></script> should be written as high as possible, respectivly within the <head> Tags. But the code above do not work --> Why?? The code works only if my script is written/loaded after the <input> Tag. Is this works as desinged? Should the script import really written at the end of the HTML page? Thanks in advance. Edited May 20, 2020 by noobdesigner Link to comment Share on other sites More sharing options...
Ingolme Posted May 20, 2020 Share Posted May 20, 2020 The page loads in order from top to bottom and the Javascript runs as soon as it can even if the rest of the page has not loaded yet. One way to solve it is to always put scripts before the closing </body> tag. Another way is to have the code wait for the page to load before assigning the event listener. This can be done with the DOMContentLoaded event: window.addEventListener("DOMContentLoaded", attachEvents); function attachEvents() { var p = document.getElementById("btn"); p.addEventListener ("click", test); } function test() { alert("Test"); } Link to comment Share on other sites More sharing options...
noobdesigner Posted May 20, 2020 Author Share Posted May 20, 2020 Ok, thank you very much. So that is how its works.The Book i am working on, did not say anything about it... Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now