1

Is it possible to have mouseleave effect always EXCEPT if the cursor is over a certain element?

So say I have two divs called div1 and div2, I would get the mouseleave effect by doing:

$('div.div1').mouseleave(function() {
    alert('code');
});

Could I have the same effect UNLESS the cursor is over div2 after the mouse moves away from div1 ?

Olivera Kovacevic
  • 697
  • 1
  • 10
  • 17
  • Hi check this answer http://stackoverflow.com/a/5018955/2887133 I guess you want some like that. – DaniP Jan 28 '14 at 14:30

4 Answers4

17

JS Fiddle here: http://jsfiddle.net/HBCWs/

$( function() {
    $('.div1').mouseleave( function(e) {
        if( ! $(e.toElement).hasClass('div2') ) {
            alert( 'not div2!' );
        }
    });
});

You can use the toElement property of the jquery event object to check which element the mouse moved to after leaving .div1

Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
3

Might this thread be of help?

Check what element the cursor is on upon mouseleave() with jQuery?

He seems to want to do something similar, and this was accepted as an answer:

You need to use event.toElement || e.relatedTarget:

$('li').mouseleave(function(e) {

// new element is: e.toElement || e.relatedTarget 

});

Or have I misunderstood your question?

Community
  • 1
  • 1
Avisari
  • 101
  • 1
  • 4
1
$('div.div1').not('div2').mouseleave(function() {
alert('code');
});

http://api.jquery.com/not/

loveNoHate
  • 1,549
  • 13
  • 21
0

Check below fiddle, when mouse leaves div1, an alert message is displayed, but when mouse leaves div2, event is not triggered.

http://jsfiddle.net/ACuE8/

$('div#div1').mouseleave(function() {
  alert("In div 1");
});