Question

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)

Was it helpful?

Solution

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

OTHER TIPS

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
}

put the event on child elements only

var menu = document.getElementById("menu");
for( var counter = 0; counter< menu.childNodes.length; counter++)
{
    menu.childNodes[ counter ].addEventListener('mouseover', function(){
      alert( "id is  " + this.id  ); 
    }, false);
}

http://jsfiddle.net/neuroflux/ssSnN/

and

$('#menu').children("li").on('mouseover', function() {
    var childID = $(this).attr("id");
    //YOUR ID WILL BE childID!
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top