Search code examples
javascripthtmlcssdom-eventsmouseevent

Javascript return id of the element that triggers the event


I have a range of divs (projects) which have a display:none-ed overlay container inside of them, containing additional info.

If the mouse enters the outer div, that overlay container should receive another class making it visible. On mouse leaving the class should be removed.

I solved it using onmouseover="setactive('DIV ID')", but it made the code look pretty messed up so I tried to switch to Eventlisteners. It won't work though and I can't figure out why. This is my script so far:

// Init Eventlisteners for each container

        window.addEventListener("load", start, false);
        function start() {
            var project_containers = document.getElementsByClassName('content-project')
            for (var i = 0; i < project_containers.length; i++) {
                project_containers[i].addEventListener("mouseover", setactive(), false)
                project_containers[i].addEventListener("mouseout", setinactive(), false)
            }
        }



// If mouse is over container, add overlay_active class

        function setactive() {
            var container = document.getElementById(event.currentTarget);
            var overlay_class = container.getElementsByClassName("element-overlay")[0];
            if (!(overlay_class.className.match(/(?:^|\s)overlay_active(?!\S)/))) {
                overlay_class.className += " overlay_active";
            }
        }



// If mouse is outside the container again, remove overlay_active class

        function setinactive() {
            var container = document.getElementById(event.currentTarget);
            var overlay_class= container.getElementsByClassName("element-overlay")[0];
            if (overlay_class.className.match(/(?:^|\s)overlay_active(?!\S)/)) {
                overlay_class.className = overlay_class.className.replace(/(?:^|\s)overlay_active(?!\S)/g, '')
            }
        }

Solution

  • You don't need the id to set container, your functions could be like this:

    function setinactive(e) {
        var container = e.currentTarget;
            //your code
        }
    }
    

    And then the call:

    project_containers[i].addEventListener("mouseout", setinactive, false);