Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jQuery toggle continually changing on mouse movement/hover

I've just got this bit of code working in jQuery via an answer on here -

$('.folder-items a').hover(function(){
   $(this).siblings('.file-hover').toggle();
});​

the .folder-items a is within a li. I want to be able to hover the whole 'li' and not just on the actual <a> to show the .file-hover div.

I've created this in jsfiddle - http://jsfiddle.net/8Sefc/8/ - but when moving my mouse around the li it's showing/hiding like crazy...

I think it's something up with my CSS and display: block; width: 100%; of the li and li a but can't work out another way to do this...

Ideas?

like image 496
Stuart Robson Avatar asked Jul 26 '26 10:07

Stuart Robson


2 Answers

The fact that the elements to be shown are "on top" of the hovered element is causing trouble. I'd suggest, as an alternative, to only show the element during the hover, hiding them when they are hovered out:

$('.folder-items a').hover(function(){
    $(this).siblings('.file-hover').show();
}).siblings('.file-hover').hover(
    function() { },
    function() { $(this).hide(); }
);

Update: this is not a perfect solution. If you move your mouse like crazy over the itens, sometimes they will "stick" and not disappear... Maybe a better solution would be to bind the hover to the parent element instead:

$('.folder-items a').parent().hover(
    function(){
        $(this).children('.file-hover').show();
    },
    function(){
         $(this).children('.file-hover').hide();
         $(this).children('a').show();
    }
);

I tested this with your fiddle, and it seems allright.

like image 99
mgibsonbr Avatar answered Jul 29 '26 04:07

mgibsonbr


The problem is because when you only supply toggle() with one function, that function is called on both mouseenter and mouseleave events - further information

If you change your code to use mouseenter() and add another handler to the .file-hover elements to hide them on mouseleave() it should work as you are expecting it to:

$('.folder-items > li > a').mouseenter(function() {
    $(".file-hover").hide();
    $(this).siblings('.file-hover').show();
});

$(".file-hover").mouseleave(function() {
    $(this).hide();
});

Updated fiddle

Update I've also included a method to fix the issue which mgibsonbr mentioned where the hover state is not removed when the mouse is scanned across the elements quickly.

like image 38
Rory McCrossan Avatar answered Jul 29 '26 04:07

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!