Design comparison
Solution retrospective
I encountered a problem on where I placed my script and this affected whether my js function was called or not on button click. If I placed it in the head section, on button click the function was not called but if placed it immediately after the button element, the function is called successfully. In some other cases, for the function to be called, its vice versa. If anybody has a well understanding of JS, how does this come about ??
Community feedback
- @peanutbutterjllyPosted over 1 year ago
hey 👋,
When JavaScript code is placed at the top of an HTML webpage, it may not work as expected because the JavaScript code gets executed before the HTML content is fully loaded and parsed by the browser. This can lead to issues when the JavaScript code relies on accessing HTML elements or interacting with the DOM (Document Object Model).
To avoid this issue, it is recommended to place JavaScript code at the bottom of the HTML file, just before the closing </body> tag. This ensures that the HTML and CSS have been fully loaded before the JavaScript code is executed, which can prevent issues with the JavaScript code
Another solution is to use the defer attribute in the tag. This attribute tells the browser to defer the execution of the script until the HTML and CSS have been fully loaded.
StackOverflow: javascript at bottom of webpage
hope my info and that stack overflow question helped!
oh and by the way, your page/solution looks great!
Marked as helpful1@calebomondiPosted over 1 year ago@peanutbutterjlly Now I know better, and thank you for the complement.
1
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord