12
$('.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

Mat
  • 202,337
  • 40
  • 393
  • 406
Wasim A.
  • 9,660
  • 22
  • 90
  • 120

8 Answers8

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

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

mathheadinclouds
  • 3,507
  • 2
  • 27
  • 37
  • 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 Jul 05 '13 at 15:57
16

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

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
6

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.

Community
  • 1
  • 1
Connell
  • 13,925
  • 11
  • 59
  • 92
2
x.filter(':hover').length

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

l00k
  • 1,525
  • 1
  • 19
  • 29
2

Try something like this-

$('.xx').hover(function(){        
        alert('d');
    }, function() {
       alert('f);
    });
rogerlsmith
  • 6,670
  • 2
  • 20
  • 25
1

why dont you just use .hover?

$(".xx").hover(function(){
    alert("d");
});
Evan
  • 5,975
  • 8
  • 34
  • 63
0

Try something like this

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

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

FRAGnat
  • 53
  • 1
  • 5
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>
Legends
  • 21,202
  • 16
  • 97
  • 123