Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - techniques for extending 'perimeter' for mouseout?

I would like to implement behaviour such that a mouseover/hover event is triggered when the mouse pointer hovers over a certain div, but such that the mouseout event tiggers not when the pointer leaves the div, but when it leaves the area 10px ourside the div.

Is there any way of achieving this that doesn't involve creating a larger parent div to bind the mouseout event to?

like image 862
UpTheCreek Avatar asked Sep 06 '11 07:09

UpTheCreek


2 Answers

My comment got me interested to see if it was possible and it's actually quite easy. No idea how well it would run in different browsers and with lots of divs but it works in this example:

http://jsbin.com/exulef/2/edit

var hello = $('#hello');
var position = hello.offset();
var height = hello.height();
var width = hello.width();

$(document).mousemove(function(e) {
  if (hello.data('inside')) {
    if ((e.pageX < position.left - 10 || e.pageX > position.left + width + 10) || 
       (e.pageY < position.top - 10 || e.pageY > position.top + height + 10)) {
      hello.text(position.top + " : " + position.left + " : " + e.pageX + " : " + e.pageY + "  Outside")
        .data('inside', false);
    }
  }
  else {
    if ((e.pageX > position.left && e.pageX < position.left + width) && 
        (e.pageY > position.top && e.pageY < position.top + height)) {
      hello.text(position.top + " : " + position.left + " : " + e.pageX + " : " + e.pageY + "  Inside")
        .data('inside', true);
    }
  }  
});

hello is just a square div. Would be quite easy to turn into a plugin as well which I might do later, lol.

Edit - I did make this into a plugin in the end: http://jmonkee.net/wordpress/2011/09/07/jquery-extended-hover-plugin/

like image 60
Richard Dalton Avatar answered Nov 01 '22 17:11

Richard Dalton


There is a way to do that without an external div, but it imply that your div will have a margin even when not hovered.

It uses the fact that the padding is inside the div, and the margin is outside.

  • When nothing happens, we have a margin, we have to go inside the div to hover.

  • When it's hovered, the margin becomes padding, this way we're inside the div for a little bit more when the mouse leaves the div.

  • When we're leaving the padding, it's back to margin.

The css is something like:

.a{
   margin:10px;
}
div.b{
   padding:10px;
   margin:0;
}

Note that it's important to have a b selector that's a bit more specific in order to have it apply without using important and without taking attention of the order.

The js would be:

$(".a").bind("mouseenter",function(){
    $(this).addClass("b");
}).bind("mouseleave",function(){
    $(this).removeClass("b");
});

Example here: http://jsfiddle.net/ynecV/

like image 1
Py. Avatar answered Nov 01 '22 19:11

Py.