13
$('.xx').mouseenter(function(){
  if($(this).is(':hover'))
    alert('d');
  else
     alert('f');
});

Here is my code, it should alert 'd' but every time it alerts 'f' What's error Here

8 Answers 8

33
function idIsHovered(id){
    return $("#" + id + ":hover").length > 0;
}

http://jsfiddle.net/mathheadinclouds/V342R/

1
  • 1
    This works perfectly. I'm not sure why this isn't upvoted. It accomplishes exactly what the OP needs, without having to set flags all over your code.
    – friggle
    Commented Jul 5, 2013 at 15:57
17

:hover is a CSS pseudo-class, not a jQuery selector. It cannot be reliably used with is() on all browsers.

3
  • 1
    so how will i check is mouse over an element or not
    – Wasim A.
    Commented Nov 4, 2011 at 14:00
  • The link in Connell's answer is quite helpful. Commented Nov 4, 2011 at 14:02
  • 1
    @Rocket, and you would be right, on Firefox and Chrome at least. However, Internet Explorer 8 does not seem to support that. Commented Nov 4, 2011 at 14:10
5

As Frederic said, :hover is part of CSS and is not a selector in jQuery.

For an alternative solution, read How do I check if the mouse is over an element in jQuery?

Set a timeout on the mouseout to fadeout and store the return value to data in the object. Then onmouseover, cancel the timeout if there is a value in the data.

Remove the data on callback of the fadeout.

2

Try something like this-

$('.xx').hover(function(){        
        alert('d');
    }, function() {
       alert('f);
    });
1
  • 1
    how it's help me to check parent's hover out ! Commented Nov 21, 2012 at 4:37
2
x.filter(':hover').length

This may be also usable when you already had queried some objects / or inside callback function.

1

why dont you just use .hover?

$(".xx").hover(function(){
    alert("d");
});
0

Try something like this

flag = ($('.xx:hover').length>0);

So you can find out if the mouse is, the object

0

Here is a little jQuery plugin that checks if the mouse is over an element.

Usage:

$("#YourElement").isMouseOverMe();

Example:

(function($) {

  var mx = 0;
  var my = 0;

  $(document).mousemove(function(e) { // no expensive logic here
    mx = e.clientX; 
    my = e.clientY;
  })

  $.fn.isMouseOverMe = function() {

    var $el = $(this);
    var el_xmin = $el.offset().left;
    var el_ymin = $el.offset().top;
    var el_xmax = el_xmin + $el.width();
    var el_ymax = el_ymin + $el.height();
    return mx >= el_xmin && mx <= el_xmax && my >= el_ymin && my <= el_ymax;
  };

}(jQuery));

$(document).mouseup(function(e) {
  console.log($("#div").isMouseOverMe())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Click inside or outside of the yellow box</h2>
<div id="div" style="width:200px;height:200px;background-color:yellow;margin-top:50px"></div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.