Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding event listeners with Javascript DOM

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?

like image 397
AlexDev Avatar asked Jan 13 '23 20:01

AlexDev


2 Answers

  1. There is no such event onmouseover, the event is called mouseover.
  2. You have to pass a function reference to 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.

like image 57
Felix Kling Avatar answered Jan 19 '23 10:01

Felix Kling


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().

like image 21
Pointy Avatar answered Jan 19 '23 12:01

Pointy