TheGr8_Nik
TheGr8_Nik

Reputation: 3200

Hover not right when element moves

I have a dynamic div, and I want to know when the mouse is hover this div. I tryed with .is( ':hover' ) but doesn't work.

jsFiddle demo

In the demo I have made a moving div and if I doesn't move the mouse the log is never called, but if I put manually the mouse hover the box it write always the logs.

Never detected

Never writes the log in the console.

Always detected

Always writes the log in the console, even the box is gone.

It's a bug or I have made a mistake? How can I detect the hover properly?

Upvotes: 0

Views: 179

Answers (1)

ZiNNED
ZiNNED

Reputation: 2650

You should be tracking the mouse movement with the mousemove() event and check the last known position of the mouse on the movement of the div.

Example:

HTML & CSS:

.red-box {
    display : inline-block;
    position : absolute;
    width : 50px;
    height : 50px;
    top : 10px;
    left : 0px;
    background-color : red;
}
#wrapper {
    height: 100vh;
    width: 100vw;
}

<div id="wrapper">
    <div class="red-box"></div>
</div>

JavaScript:

var posX = 0;
var step = 10;
var maxX = 200;
var mouseX = -1;
var mouseY = -1;
var entered = false;
var $box = $('.red-box');

setInterval(function () {
    posX += step;
    if (posX >= maxX) 
        posX = 0;
    $box.css("left", posX);

    var top = $box.offset().top;
    if (mouseX >= posX && mouseX <= (posX + $box.width()) && mouseY >= top && mouseY <= (top + $box.height())) {
        console.log("mouse entered");
        entered = true;
    } else if (entered) {
        console.log("mouse left");
        entered = false;
    }
}, 500);

$("#wrapper").on("mousemove", function (e) {
    mouseX = e.pageX - $(this).position().left;
    mouseY = e.pageY - $(this).position().top;
}).on("mouseleave", function()
{
    mouseX = -1;
    mouseY = -1;
});

FIDDLE

Edit: Added a new mouseleave() event to the wrapper.

Upvotes: 2

Related Questions