Javascript syntax error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 2

Javascript syntax error

btn.addEventListener('click'change); Renders perfect in all browsers except Sololearn editor js section it gives syntax error? const btn = document.getElementById('button'); const rainbow = ['red','orange','yellow','green','blue','rebeccapurple','violet']; function change() { document.body.style.background = rainbow[Math.floor(7*Math.random())]; } btn.addEventListener('click'change);

3rd Nov 2017, 3:43 PM
Dawie Prinsloo
Dawie Prinsloo - avatar
13 Answers
+ 8
@Netkos is half right: you must add the missing coma, but you must not add parenthesis to your callback function (change): btn.addEventListener('click', change); But where is located your script on code playground? If it's in JS tab, you must wait for document loaded before getting the 'btn' reference... or you'll get another error about 'addEventListener' not reachable on undefined ^^
3rd Nov 2017, 4:07 PM
visph
visph - avatar
+ 6
You didn't add the coma, and you need to wait for document loaded: window.onload = function() { const btn = document.getElementById('button'); const rainbow = ['red','orange','yellow','green','blue','rebeccapurple','violet']; function change() { document.body.style.background = rainbow[Math.floor(7*Math.random())]; } btn.addEventListener('click',change); };
3rd Nov 2017, 4:19 PM
visph
visph - avatar
+ 4
Share you code (the link of the playground project or make it public): the addEventListener method works well here ^^
3rd Nov 2017, 4:14 PM
visph
visph - avatar
+ 4
I'm trying not to interfere, so just noting that it will work here :)
3rd Nov 2017, 4:18 PM
Kirk Schafer
Kirk Schafer - avatar
+ 4
You forgot my last line closing the main function: };
3rd Nov 2017, 4:48 PM
visph
visph - avatar
+ 4
SYNTAX: element.addEventListener(event, function, useCapture) CHANGE TO: btn.addEventListener('click', change);
3rd Nov 2017, 4:55 PM
AgentSmith
+ 4
@Dawie Prinsloo wrote: << now it's working perfectly. >> NOW? It could be working since my first post, if you had read it more closely ;P
3rd Nov 2017, 5:02 PM
visph
visph - avatar
+ 3
@visph Thanks for correcting. :D Habit.
3rd Nov 2017, 4:54 PM
AgentSmith
+ 1
its public
3rd Nov 2017, 4:16 PM
Dawie Prinsloo
Dawie Prinsloo - avatar
+ 1
Nope still gives syntax error on btn.addEventListener('click',change); the code work perfectly in other browsers
3rd Nov 2017, 4:43 PM
Dawie Prinsloo
Dawie Prinsloo - avatar
0
Now it produce a uncaught type error on line 4. l think Sololearn editor dont support the addEventListener() method... It work fine in Firefox and Google Chrome..
3rd Nov 2017, 4:08 PM
Dawie Prinsloo
Dawie Prinsloo - avatar
0
Bravo! Thanks visph now it's working perfectly.
3rd Nov 2017, 4:54 PM
Dawie Prinsloo
Dawie Prinsloo - avatar
0
😅
3rd Nov 2017, 5:18 PM
Dawie Prinsloo
Dawie Prinsloo - avatar