JQuery hover loop
Asked Answered
M

1

8

I have a problem with this JQuery code:

$(".item").mouseenter(function(){
    $(this).addClass("active");
    $(this).removeClass("item");
    $(".item").hide(700);
}).mouseleave(function(){
    $(this).stop();
    $(this).addClass("item");
    $(this).removeClass("active");
    $(".item").show(700);
});

and this is my HTML:

<ul>
    <li class="item">Item</li>
    <li class="item">Item</li>
    <li class="item">Item</li>
    <li class="item">Item</li>
    <li class="item">Item</li>
</ul>

I want when I do hover on one item, other items be hide, the code works fine but the problem is there if I hover another item in duration of hiding (700 ms), it will make a loop of hide/show items. what can I do for prevent this.

jsFiddle

note: I want the hovered item goes to left, not stay fixed.

Matlick answered 2/11, 2013 at 16:39 Comment(1)
bad UI concept simply because you can't avoid hovering another due to floats. As they animate they shift positions. WOuld animating opacity work for you?Barnes
L
3

You were using float: left to the li elements.. so the ul was with no width and height. Apply this CSS:

ul {
    overflow: auto;
}

and also I made some changes in jQuery:

$(".item").on('mouseenter', mEnter)
$('ul').on('mouseleave', function () {
    $('.item').stop();
    $('.active').removeClass("active")
        .addClass("item");
    $(".item").show(700);
});

function mEnter() {
    $(this).addClass("active");
    $(this).removeClass("item");
    $(".item").hide(700);
}

you were applying mouseleave event to the individual hovered LI element instead of the parent element i.e UL.

Working Fiddle

Laurent answered 2/11, 2013 at 17:10 Comment(2)
Nicely done... this seems to work just as the OP is intending.Threepence
btw, no need of wrapping in a function.. I just did it while testing.Laurent

© 2022 - 2024 — McMap. All rights reserved.