Trick for Targeted Unload Events JQuery

Monday, March 7th, 2011

Insert my typical caveat here. There may be better solutions to this out there, but as a hasty mechanism, it seems to work.

I needed to have a confirmation dialog pop up on leaving an administrative page, asking if the user wants to send data to someone. The problem is the form also receives self-referential posts as well as a paged data set, so I didn’t want to reconstruct the entire page around this simple need.

Enter JQuery. Within $(document).ready, this works well, but it triggers on every unload.

$(window).bind('unload'), function() { // function here });

But the problem is that paging nav and posts fire the same event.
So I add a check for a reusable hidden field value.

$(window).bind('unload',function(){
if ( $("#unloadbindingvar").val() != 1 ) {
var answer = confirm('Yes, no, maybe so');
if (answer) {
// do something
} else {
return true; //and let them continue on their merry way
}
}
});

Then, on form submit, set that value and return true.

$("form").submit(function() {
$("#unloadbindingvar").val("1");
return true;
}

But what to do about GETs from href paging nav? Easy, add a class to your nav, if one isn’t there already, and simply hit them in $(document).ready this way.

$("a.nav").click(function(){
$("#unloadbindingvar").val("1");
return true;
});

Works fairly well for what I’m trying to achieve.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.