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)
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;
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With