I'm currently trying to programm my first Website. Therefore I want to get all Elements with a certain class an give them all the same EventListeners. I did that like this:
const certs = document.getElementsByClassName("certificate");
for (var i = 0; i < certs.length; i ) {
certs[i].addEventListener("mouseover", mouseOver());
certs[i].addEventListener("mouseout", mouseOut());
}
function mouseOver() {
this.querySelector(".overlay").classList.add("active");
}
function mouseOut() {
this.querySelector(".overlay").classList.remove("active");
}
My Problem is, "this" doesnt seem to be the element which is triggering the mouseOver event. I also tried puting "this" as a parameter like here:
const certs = document.getElementsByClassName("certificate");
for (var i = 0; i < certs.length; i ) {
certs[i].addEventListener("mouseover", mouseOver(this));
certs[i].addEventListener("mouseout", mouseOut(this));
}
function mouseOver(elem) {
elem.querySelector(".overlay").classList.add("active");
}
function mouseOut(elem) {
elem.querySelector(".overlay").classList.remove("active");
}
Both ways didnt work and know I am stuck in a way... Is there a way to do this? How can I use the exact element triggering the event?
(I dont want to give every element a unique ID to make it reusable)
CodePudding user response:
The second argument of addEventListener
is a function. Right now, you're calling the function immediately, which returns undefined
, so whenever you move your mouse over or out it attempts to run undefined
. Pass just the function variable itself, addEventListener
will handle calling the function later.
addEventListener
calls the callback function with an Event
object, which has the property target
which is how you get your element.
const certs = document.getElementsByClassName("certificate");
for (var i = 0; i < certs.length; i ) {
certs[i].addEventListener("mouseover", mouseOver);
certs[i].addEventListener("mouseout", mouseOut);
}
function mouseOver(event) {
event.target.querySelector(".overlay").classList.add("active");
}
function mouseOut(event) {
event.target.querySelector(".overlay").classList.remove("active");
}