I'm having trouble adding eventListener to through javascript. Ok, I have a function that creates 4 anchor elements. I want to add an event to them onmouseover that calls a function to change their backkground color. Here's the code (look at the next to last line of createAnchor() to find the relevant code line.
function createAanchor(index) {
var a = document.createElement("a");
var text = getText(index);
var a = document.createElement("a");
var t = document.createTextNode(text);
a.href = getHref(index);
a.appendChild(t);
a.style.textAlign = "center";
a.style.fontSize = "1.2em";
a.style.color = "white";
a.style.fontFamily = "arial";
a.style.fontWeight = "bold";
a.style.textDecoration = "none";
a.style.lineHeight = "238px";
a.style.width = "238px";
a.style.margin = "5px";
a.style.background = eightColors(index);
a.style.position = "absolute";
a.addEventListener("onmouseover", changeColor());
return a;
}
function changeColor() {
alert("EVENT WORKING");
}
Ok here's the problem. When the function gets to a.addEventListener("onmouseover", changeColor());
the function changeColors()
executes, but it does not execute later on onmouseover
Why is this?
onmouseover
, the event is called mouseover
.addEventlistener
. ()
calls the function, as you already noticed, so... don't call it.This is how it should be:
a.addEventListener("mouseover", changeColor);
I recommend to read the excellent articles about event handling on quirksmode.org.
It's because you wrote changeColors()
instead of just changeColors
. The ()
tell JavaScript to call the function.
In other words, changeColors
by itself is a reference to the function, while changeColors()
refers to the function and then calls it. The result of the function call (the return value from the function) is what's ultimately passed to addEventListener()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With