Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to check if the mouse is over an element

Tags:

jquery

I have a deferred function that binds a mouseenter event:

$(window).load(function(e) {
  var $container = $('.container');
  $container.mouseenter(function(e) {
    //do something
  });
  ...
});

The problem is the mouse might already be over the element when the load event fires, hence before the mouseenter event was bound.
I can get around this by putting some code at the end of the page load handler to do a one-time check if the mouse is inside the element and trigger the mouseenter event manually:

// check if the mouse is inside $container
if(mouse is inside $container)
  $container.mouseenter();

How can I check if the mouse is over the element in the load event?

I tried $container.is(':hover') but it doesn't work.

like image 615
spb Avatar asked Dec 21 '11 23:12

spb


1 Answers

i dont test it yet but think you want like this...

function checkMouseCollision(obj) {
    var offset = obj.offset();
    objX= offset.left;
    objY=offset.top;
    objW=obj.width();
    objH=obj.height();

    var mouseX = 0;
    var mouseY = 0;
    $().mousemove( function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
    });

    if((mouseX>objX&&mouseX<objX+objW)&&(mouseY>objY&&mouseY<objY+objH)){
        alert("hovered")     
    };
};
checkCollision($(".box"))
like image 194
Salt Hareket Avatar answered Oct 12 '22 20:10

Salt Hareket