gordyr
gordyr

Reputation: 6276

How to prevent mouseleave from firing when an element is following the mouse?

The code below moves a div to the correct height upon mouseenter of another element (which I will refer to as 'container' from now on), then as the mouse moves it adjusts the left position of the element so that it follows the mouse left and right.

Finally when the mouse leaves the container div, the element is hidden.

$('body').on('mouseenter mouseleave mousemove', '.seek-bar', function (e) {
    var $seeker = $('#seek-head');

    if (e.type == 'mouseenter') {
        var top = Number($(this).offset().top);
        $seeker.css({ top: top + 'px' }).show();
    }
    else if (e.type == 'mouseleave') {
        $seeker.hide();
    }

    if (e.type == 'mousemove') {
        var x = e.pageX;
        $seeker.css({ left: x + 'px' });
    }
});

Although this works fine, the element flashes due to the mouse being over $seeker rather than the container element. The mouseleave event is being fired when I don't wan't it to be.

How can I prevent this?

Please Note: The $seeker element is directly in the <body> so will always be 'in front' of the container element.

Upvotes: 0

Views: 1737

Answers (1)

MarkSmits
MarkSmits

Reputation: 538

Rewrote you code a litte, but why don't you put the mouseleave on the element that is infront of the container element?

var $seeker = $('#seek-head');    
$('body').on({
    mouseenter: function() {
        var top = Number($(this).offset().top);
        $seeker.css({ top: top + 'px' }).show();
    },
    mousemove: function() {
        var x = e.pageX;
        $seeker.css({ left: x + 'px' });
    }
}, '.seek-bar');

$('body').on('mouseleave', $seeker, function() {
    $seeker.hide();
});

Upvotes: 2

Related Questions