Pieter
Pieter

Reputation: 32755

How to tell if a mouse is hovering over an element

Is there a function I can call to know if a certain element is currently being hovered over, like this?

/* Returns true or false */
hoveringOver("a#mylink");

Upvotes: 7

Views: 20759

Answers (3)

SLaks
SLaks

Reputation: 887215

You can use jQuery's hover method to keep track:

$(...).hover(
    function() { $.data(this, 'hover', true); },
    function() { $.data(this, 'hover', false); }
).data('hover', false);

if ($(something).data('hover'))
    //Hovered!

Upvotes: 9

Jon
Jon

Reputation: 6036

I have no idea if this would be the best way to do this but if you are using jquery, you could do something like this:

var hoveringOver = false;

$("a#myLink").bind("mouseenter", function(){
hoveringOver = true;
});

$("a#myLink").bind("mouseleave", function(){
hoveringOver = false;
});

function isHoveringOver(){
return hoveringOver;
}

Upvotes: 1

Pekka
Pekka

Reputation: 449385

Yes, in classic JS:

document.getElementById("mylink").onmouseover = function() { alert("Hover!"); }
document.getElementById("mylink").onmouseout  = function() { alert("Out!"); }

in jQuery:

$('#mylink').mouseover(function() {
  alert("Hover!");
});

Upvotes: 8

Related Questions