Wasim A.
Wasim A.

Reputation: 9890

Jquery condition check is(':hover') not working

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

Upvotes: 13

Views: 44560

Answers (8)

Legends
Legends

Reputation: 22672

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>

Upvotes: 0

l00k
l00k

Reputation: 1545

x.filter(':hover').length

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

Upvotes: 2

FRAGnat
FRAGnat

Reputation: 53

Try something like this

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

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

Upvotes: 0

mathheadinclouds
mathheadinclouds

Reputation: 3725

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

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

Upvotes: 33

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

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

Upvotes: 17

rogerlsmith
rogerlsmith

Reputation: 6786

Try something like this-

$('.xx').hover(function(){        
        alert('d');
    }, function() {
       alert('f);
    });

Upvotes: 2

Evan
Evan

Reputation: 6115

why dont you just use .hover?

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

Upvotes: 1

Connell
Connell

Reputation: 14411

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.

Upvotes: 5

Related Questions