brandker brandker - 2 months ago 9
Javascript Question

Why isn't addEventListener working for this project?



document.getElementById('btn').addEventListener("onclick", mouseover);

function mouseover() {
this.style.color = " yellow ";
this.style.backgroundcolor = "green";
}

<input type="button" value= "Submit" id="btn" />




Answer

To attach a listener to an event named click, you need to do either of the following:

object.onclick = function(event) { ... }
object.addEventListener('click', function(event) { ... });

There's no "on" before the event name in the second approach, so in your case, your code should be:

var btn = document.getElementById('btn');
btn.addEventListener("click", mouseover);
                   // ^-- note no "on" here

function mouseover() {
  this.style.color = "yellow";
  this.style.backgroundColor = "green";
}
<input type="button" value= "Submit" id="btn" />

(Also note that it's backgroundColor, not background.color, and there should be no spaces within the color strings.)