Stuart Robson
Stuart Robson

Reputation: 1149

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?

Upvotes: 3

Views: 326

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337610

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.

Upvotes: 3

mgibsonbr
mgibsonbr

Reputation: 22007

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.

Upvotes: 6

Johan
Johan

Reputation: 35193

Well, for starters, I would suggest changing

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

to something like

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

Upvotes: 1

Related Questions