Home > database >  Find exact Position in NodeList on MouseEvent
Find exact Position in NodeList on MouseEvent

Time:10-10

Seems obvious but can't find a solution.I have a couple of Div's with the same class and when you hover over them I want to know which one you exactly hovered, as a NodeList Position Value.

HTML

<div id="summary">

    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>
    <div class="articles"></div>

</div>

JS

let articles = document.querySelectorAll(".articles");

    for (let x of articles) {

        x.addEventListener('mouseenter', (e) => {

            p = Exact Position in Nodelist??
    
            console.log(articles[p]);

        });
    }

Thank you.

CodePudding user response:

Here is a simple solution I came up with:

let articles = document.querySelectorAll(".articles");

for (let [position, article] of articles.entries()) {
 
  article.addEventListener('mouseenter', (e) => {
    
    console.log(position) // Exact Position in Nodelist
    console.log(articles[position]) // The Node hovered

  });

}

Hope my help is useful.

CodePudding user response:

You should take the parent node's children and find its index like below.

Try this

let articles = document.querySelectorAll(".articles");

for (let x of articles) {
  x.addEventListener("mouseenter", (e) => {
    console.log([...e.target.parentNode.children].indexOf(e.target));
  });
}

Code sandbox => https://codesandbox.io/s/young-frost-x6u1x?file=/src/index.js

CodePudding user response:

You can use mouseover on the parent, this way you will only add one listener:

let articles = document.querySelectorAll(".articles");
var summary = document.getElementById("summary");
summary.addEventListener("mouseover", (e) => {
  if (e.target.classList.contains("articles")) {
    let position = Array.from(e.target.parentNode.children).indexOf(e.target);
    console.log(position,articles[position]);
  }
});
.articles {
  width: 100px;
  height: 100px;
  border: solid 1px red;
}
<div id="summary">

  <div class="articles">a</div>
  <div class="articles">b</div>
  <div class="articles">c</div>
  <div class="articles">d</div>
  <div class="articles">e</div>
  <div class="articles">f</div>
  <div class="articles">g</div>

</div>

  • Related