hello I have the following code, the problem is that when iterating with forEach it affects all the elements of the nodeList that are 3 how could I do to affect it only generates the call to the eventListener?? I need that when I mouse over one of the projects it affects only this one and not the rest
const $projects = document.querySelectorAll(".projects__grid__element")
$projects.forEach( (project,index) => {
addEventListener('mouseover', (event) => {
// const $projectDescription= project.querySelector(project[index]);
// $projectDescription.style.display= "flex"
});
addEventListener('mouseout', (event) => {
// const $projectDescription= project.querySelector(".projects__grid__element__description");
// $projectDescription.style.display = "none"
});
})
I need that when I mouse over one of the projects it affects only this one and not the rest
CodePudding user response:
You're using addEventListener
, so the event listener is attached with window
. But as you want the event listener to be attached on each project instead, so you should use project.addEventListener
.
like this:
const $projects = document.querySelectorAll(".projects__grid__element")
$projects.forEach( (project,index) => {
project.addEventListener('mouseover', (event) => {
// const $projectDescription= project.querySelector(project[index]);
// $projectDescription.style.display= "flex"
});
project.addEventListener('mouseout', (event) => {
// const $projectDescription= project.querySelector(".projects__grid__element__description");
// $projectDescription.style.display = "none"
});
})
And its better if you attach the event listener to the parent of $projects
element, so when you later remove or add new project elements into it the event listener will work, no extra work needed.
CodePudding user response:
You are adding event listeners to window itself not to the element from nodelist.
You can try:
forEach loop:
const $projects = document.querySelectorAll(".projects__grid__element");
Array.prototype.forEach.call($projects, function (project, index) {
project.addEventListener('mouseover', (event) => {
project.style.display= "flex"
});
project.addEventListener('mouseout', (event) => {
project.style.display = "none"
});
})
for loop:
const $projects = document.querySelectorAll(".projects__grid__element");
for (let index = 0; index < $projects.length; index ) {
let project = $projects[index];
project.addEventListener('mouseover', (event) => {
project.style.display= "flex"
})
project.addEventListener('mouseout', (event) => {
project.style.display = "none"
})
}