Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ID of a child when mouseover parent

I guess that my question is quite simple but I'm a real beginner in JavaScript and I can't find what I am looking for:

I am trying to get the ID of a li when mouse is over the nav or ul... My HTML structure would be:

<nav><ul id="menu">
<li id="FirstLink">Link1</li>
<li id="SecondLink">Link2</li>
<li id="ThirdLink">Link3</li>
</ul></nav>

So my goal is to listen for a mouseover (and mouseout) event on each li, but a script with 10 listener (for 5 li) is too much dirty...

That's why I thought of a script like:

var menu = document.getElementById("menu");
menu.addEventListener('mouseover', myFunction, false);

function myFunction () {
//something that get the ID of the <li> that is currently under the mouse and can put it inside a variable as "Link1"
}

But if there is a better solution, I will be happy to know it ! (I would like to stay in pure js)

like image 347
hggjvhkkfkhftrjghvgfgj Avatar asked Oct 02 '22 16:10

hggjvhkkfkhftrjghvgfgj


2 Answers

To get the ID of the hovered element you need to use event.target.
For that you need to pass event as a parameter in your function.
Then you can get the .id attribute of that element.

function myFunction(event) {
    show_result.innerHTML = event.target.id;
}

Demo here

like image 85
Sergio Avatar answered Oct 07 '22 19:10

Sergio


var menu = document.getElementById("menu");
menu.addEventListener('mouseover', myFunction, false);

function myFunction (event) {
    var li = event.target;
    if( li.nodeName !== 'li' ) return;

    // do your stuff with li
}
like image 22
redexp Avatar answered Oct 07 '22 17:10

redexp