+ 2

code playground rules - how do the html css and JavaScript windows connect?

How do the html, css, and JavaScript windows connect in the code playground? I found that some JavaScript methods such as addEventListener and getElementById would not work unless the JavaScript was embedded in the html using script tags. Thanks.

9th Jul 2018, 11:34 AM
Lisa F
Lisa F - avatar
7 Answers
+ 6
The codes on Javascript window is put onto head tag, it would not run DOM access functions due to the page is loaded later. Use window.onload to callback your DOM access functions on Javascript window.
9th Jul 2018, 11:45 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 3
Thank you Calvin! But I also have to ask Sololearn why the JavaScript is automatically inserted in the head section of the html? Wouldn't it be better to load the JavaScript at the end? That way, the entire HTML page is available to the JavaScript plus isn't loading at the end a best practice? Here's an example of using the window.onload method to make sure JavaScript loads after html loads as Calvin suggested. Thanks again! https://code.sololearn.com/W0Y1boa0Bhd4/#js
9th Jul 2018, 12:11 PM
Lisa F
Lisa F - avatar
+ 3
You could always put your Javascript codes onto and before body closing tag, in fact this is my normal practice, instead of putting it on Javascript window.
9th Jul 2018, 12:37 PM
CalviŐ˛
CalviŐ˛ - avatar
+ 3
Calvin, thank you for all of your great insights. Although Sololearn is 99% wonderful, I feel that some of these little (but very important) details are unfortunately presented in a confusing way for new coders. For example, when I look at the vast majority of the web coding examples I see html, css, and JavaScript all mashed up in the html window. Worse yet, html attributes are often used for storing styles and JavaScript. A new coder needs to know how to separate their html, css, and JavaScript into separate files. They need to know about the link tag for external css and the script tag for external JavaScript. Yikes.
9th Jul 2018, 1:02 PM
Lisa F
Lisa F - avatar
+ 2
Thanks, but I understand that much. Yet not all JavaScript methods work using the windows such as getElementById and addEventListener. Why?
9th Jul 2018, 11:40 AM
Lisa F
Lisa F - avatar
+ 1
They are connected automatically, you don't have to use tags like <link> or <script>.
9th Jul 2018, 11:38 AM
giannismach
giannismach - avatar
0
I do not know the real reasons Sololearn put the Javascript code in head tag. However, if we are writing component module codes, it's better to put it on head tag, to ensure components loaded before calling it.
9th Jul 2018, 12:35 PM
CalviŐ˛
CalviŐ˛ - avatar