开发者

How do I make a popover not flicker in jquery

开发者 https://www.devze.com 2023-02-16 15:56 出处:网络
I have a simple scenario where I have div tag which when the mouse hovers over it, displays an overlay with more information (using jquery and jquery ui). The problem I\'m getting is that the overlay

I have a simple scenario where I have div tag which when the mouse hovers over it, displays an overlay with more information (using jquery and jquery ui). The problem I'm getting is that the overlay flickers when the mouse hovers over it:

$('#myobject').hover(function() {
  $popover = $('#popover');
  $popover.show();
  $popover.position({
    my: "left top",
    at: "left to开发者_JS百科p",
    of: $(this)
  });
}, function() {
  $('#popover').hide();
});

Obviously I have to do something where moving the mouse on the popover doesn't kill the hover event, but I'm not sure how to do this. You can see the scenario running here: http://jsfiddle.net/vRH3Q/2/


Try putting the child <div> within the parent <div>:

<div id='myobject'>
    My Object
    <div id='popover'>My Popover</div>
</div>

jsFiddle


It flickers like that because the 'hover' event is attached to #myobject. When you move your mouse around, the mouse is NOT hovering over #myobject because you have #popover over top #myobject. So, you are rapidly moving between #myobject and #popover causing the flicker to happen.

A better solution is to use a combination of mouseover and mouseout.

$('#myobject').mouseenter(function() {
    $popover = $('#popover');
    $popover.show();
    $popover.position({
        my: "left top",
        at: "left top",
        of: $(this)
    });
});

$('#popover').mouseout(function() {
    $('#popover').hide();
});

I have updated your jsFiddle.


Get rid of the mouseleave event on #myobject and add it to the #popover element:

$('#myobject').bind('mouseenter',function() {
    $popover = $('#popover');
    $popover.show();
    $popover.position({
        my: "left top",
        at: "left top",
        of: $(this)
    });
});

$('#popover').bind('mouseleave', function(){
    $(this).hide();
});

Updated jsfiddle: http://jsfiddle.net/vRH3Q/2/


Once the popover div is shown jQuery thinks it is no longer hovering over myobject, move your mouse and the loop continues causing the flicker.

This works:

$('#myobject').mouseenter(function() {
    $popover = $('#popover');
    $popover.show();
    $popover.position({
        my: "left top",
        at: "left top",
        of: $(this)
    });
});

$('#popover').mouseout(function() {
    $('#popover').hide();
});

A clunky workaround (that might in certain scenarios depending on your need) to fix the "corner" problem is to make sure the popover is closed whenever the mouse goes back to the body of your page, by adding this:

$('body').hover(function() {
    $('#popover').hide();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消