0
votes

How can I trigger a function when my mouse is leaving the viewport?

I listen to the "mouseleave" event from my "html". But in firefox, "mouseleave" also be triggered on two circumstances. 1. is when the alert popup (I solve it now by add the blur/focus listener) 2. when I right click on the page, and the mouse move to the showup menu.

It seems like firefox see this behavior as "mouseleave", even my mouse is still in the page.

here is my code.

$('html').bind('mouseleave',bouncehandler);
var visted = 1;
var bouncehandler = function(e){  
    var yheight = $(window).height();
    if(e.pageX<$('body').width() && e.pageY < yheight ){
       alert('leaving');
       $('html').unbind('mouseleave',bouncehandler);
    }
}

$(window).blur(function(){
   $('html').unbind('mouseleave',bouncehandler);
}).focus(function(){
   if(visited){
       $('html').bind('mouseleave',bouncehandler);
    }
});

How can I solve this problem ? thanks

1
You can only trap UI events within the viewport, nothing outside of that like the browsers URL input box or refresh button, etc. - Lowkase
This sounds like it might lead to some extremely annoying behavior and a bad user experience. You may want to step back and rethink what you are trying to accomplish. - jbabey
@Lokase: actually, I need to trigger when the mouse leave the viewport.(sorry I didn't name it specific) - Christine Chan
@jbabey: I agree with that its annoying. But it's a one time event, and is like giving a coupon when customer is leaving our e-commercial page. - Christine Chan

1 Answers

0
votes

You can get mouse position and any mouse events only inside de viewport.

You can set an function to be executed when the browser closes, like this:

function confirmExit(){
    alert("confirm exit is being called");
    return false;
}

window.onbeforeunload = confirmExit;