views:

25

answers:

1

Hi... Anyone know how to do this:

When some user left my site by closing the browser or tab or going to other site I would like to do an action (show an alert) and if the user clicks on a link or button to other page of my own site I would like to do another action...

If I use unload event I can't differentiate between these two kind of behavior of the user... please help because I really need it.

Thanks for the help.

+1  A: 

Set a flag on all of your internal links:

var isInternal = false;
$('a[href^="http://mysite.com/"]').live('click', function() {
    isInternal = true;
});

// then in your onunload handler:

if (isInternal) {
    // perform action 1
} else {
    // perform action 2
}

A better selector for the links might be something like this:

$('a:not([href*="//"])')

But only if you never use absolute links in your own site.

nickf
I would agree with this. Then your flag on the internal links can tell you if your navagating from the page. However I believe it is important to note this will not work where you are using onClick events on elements, then using javascript to redirect. But overall This is probably your best solution.
John Hartsock
@John - depending on the order in which the click handlers are triggered, this method may still work.
nickf
would this work if my my anchor looks like `<a href="contact.php">Contact Us</a>` ?... this is still internal right?
Reigel
Thanks a lot... This method do the 90% of I want to do... The only thing that I couldn't handle and is of my interest is when I press F5 and refresh the page... I have seen that the unload event is called and is like I have left the site but I don't.
l2mt