Question

I'm trying to find the element that triggered a page exit. Say they click on an a href... I'll leave the JS-initiated location changes for another battle. I want to do some processing before exit (ie, save state of app).

What I've tried:

$(window).bind("unload", function(e) { console.log("====EXIT===="); console.log($(this)); console.dir(e); } );

Neither the $(this) nor "e" (event) reference the element that caused it.

  • $(this) is nothing
  • and "e" prints an empty object "c.Event"
Was it helpful?

Solution

i pressume this one will work for you.

$(document).ready(function(){

    $('a').click(function(event){
        var pageUrl = $(this).attr("href");
        if(pageUrl.indexOf('google.com') == -1 && !$(this).attr("rel") && pageUrl.indexOf('javascript')==-1){
            //only your domain, lightboxes, and javascripts, otherwise cancel event.
            event.preventDefault(); 
            console.log('sorry dude no another site');
        }
    });

});

Try with theese;

<a href="http://google.com">google</a>
<a href="http://yahoo.com">another site</a>
<a href="javascript:alert(1)">alert</a>
<a href="http://www.gravatar.com/avatar/b46c1b6ff31e665600a62482f197622f?s=32&d=identicon&r=PG" rel="ligthbox">image</a>

OTHER TIPS

The JavaScript event is "onBeforeUnload" and its corresponding jQuery event is 'beforeunload':

$(window).bind('beforeunload', function() {
  confirm("You know you're leaving this page, right?");
});

EDIT -

The only way to determine which element caused a URL change is to hook all of the elements on the page. For example:

var lastElementClicked;

$('a').click(function(){
  lastElementClicked = this;
});

You can then use the lastElementClicked object's attributes -- such as href, data() or html() -- in the beforeUnload to do your logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top