+ 2

Why doesn't it work?

When I use this code in the code playground it only works when I paste it under <script> tag in HTML. But when I paste it in the JavaScript tab, it gives me an error. what am I missing? html tab: <p id="demo"></p> JavaScript tab: var text = document .getElementById("demo"); text.innerHTML = "hello world";

4th Apr 2018, 9:26 AM
Kacper Orłowski
Kacper Orłowski - avatar
18 odpowiedzi
+ 2
Wrap your code in: window.onload = function(){} I think it’s because the script loads before HTML
4th Apr 2018, 9:41 AM
Chalza
Chalza - avatar
+ 1
This is how it looks and still doesn't work. https://code.sololearn.com/WN3Iv061Ek2a/?ref=app
4th Apr 2018, 9:48 AM
Kacper Orłowski
Kacper Orłowski - avatar
+ 1
Ahah you didn’t understand ^^ This: window.onload = function(){ function hmm (){ var test = document .getElementById("demo"); test.innerHTML = "HELLO"; } }
4th Apr 2018, 9:52 AM
Chalza
Chalza - avatar
+ 1
hmm is not defined.
4th Apr 2018, 10:04 AM
Kacper Orłowski
Kacper Orłowski - avatar
+ 1
Because window.onload will execute the code after the HTML document has loaded. If not, js will not recognize your html elements.
4th Apr 2018, 10:09 AM
Chalza
Chalza - avatar
+ 1
Yeah, but it’s not very easy to read it
4th Apr 2018, 10:14 AM
Chalza
Chalza - avatar
+ 1
Thanks for making things clear to me 😊
4th Apr 2018, 10:15 AM
Kacper Orłowski
Kacper Orłowski - avatar
+ 1
No problem ^^ these are basics error, don’t worry, everybody did these 😉
4th Apr 2018, 10:23 AM
Chalza
Chalza - avatar
+ 1
I will get better eventually
4th Apr 2018, 10:28 AM
Kacper Orłowski
Kacper Orłowski - avatar
0
There is no output now. I still am doing something wrong.
4th Apr 2018, 10:02 AM
Kacper Orłowski
Kacper Orłowski - avatar
0
No, just need to call your function, like this: hmm();
4th Apr 2018, 10:03 AM
Chalza
Chalza - avatar
0
Call it after your function’s declaration
4th Apr 2018, 10:06 AM
Chalza
Chalza - avatar
0
now it worked. but why do I have to call it within a window.onload scope?
4th Apr 2018, 10:08 AM
Kacper Orłowski
Kacper Orłowski - avatar
0
This is why it's recommend to put your JS at the bottom of the <body> tag.
4th Apr 2018, 10:13 AM
Kacper Orłowski
Kacper Orłowski - avatar
0
Wouldn't this be an easier way to go? https://code.sololearn.com/Wr0Fk7ajdJ4R/?ref=app
4th Apr 2018, 10:14 AM
Kacper Orłowski
Kacper Orłowski - avatar
0
There is lantency when we load the page but yes, it works
4th Apr 2018, 10:15 AM
Chalza
Chalza - avatar
0
I am trying to imprement this in a different code but I still fail. I am trying to change the value of the progress bar with user input. Do you know why it doesn't work? https://code.sololearn.com/WsM2dGQ3jp6P/?ref=app
4th Apr 2018, 10:35 AM
Kacper Orłowski
Kacper Orłowski - avatar
0
Kacper Orłowski the 2nd value the code asks is used as value for your progress bar. Why do you say it's not working?
4th Apr 2018, 12:07 PM
🤖 Basile Laderchi