Dan Dan - 6 months ago 8
Javascript Question

Manipulate only the element which the mouse hovers over jquery

I have a function in my script which is meant to manipulate the navigation of a html page. My problem is I have multiple

<nav>...</nav>
blocks of code and when I use the code below it affects all of them.

$(function () {
$('nav').hover(function () {
$('nav').animate({ top: '-=100px' }, 1000, 'easeOutBounce', null);
});
});


Therefore I assumed the logical thing to do would be specify which nav block was generating the hover event, however when using
this
inside the function fired when a hover event was in place nothing happened.

$(function () {
$('nav').hover(function () {
this.animate({ top: '-=100px' }, 1000, 'easeOutBounce', null);
});
});


How am I able to identify and manipulate the nav block which is being hovered over on its own and not affect all the nav blocks at once.

Edit

For example if I were to have these three
nav
blocks and I want them to only be manipulated by the function if the
nav
block is being hovered over, how would I differentiate between them.

<nav id="nav1"></nav>
<nav id="nav2"></nav>
<nav id="nav3"></nav>

Answer

Use $(this) instead of this

$(function () {
    $('nav').hover(function () {
        $(this).animate({top: '-=100px' }, 1000, 'easeOutBounce', null);
    });
});
Comments