- 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);
13 Respostas
+ 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 ^^
+ 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);
};
+ 4
Share you code (the link of the playground project or make it public): the addEventListener method works well here ^^
+ 4
I'm trying not to interfere, so just noting that it will work here :)
+ 4
You forgot my last line closing the main function:
};
+ 4
SYNTAX:
element.addEventListener(event, function, useCapture)
CHANGE TO:
btn.addEventListener('click', change);
+ 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
+ 3
@visph Thanks for correcting. :D Habit.
+ 1
its public
+ 1
Nope still gives syntax error on btn.addEventListener('click',change);
the code work perfectly in other browsers
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..
0
Bravo! Thanks visph now it's working perfectly.
0
đ