Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have beforeunload functionality with hashchange?

This code here works for a page refresh or closing the page. It pops up a dialog asking if you're sure you want to leave without saving.

 $(window).on('beforeunload', function(){
      return 'Did you save your changes?';
 });

Trouble is I have a SPA and I'd like this to show on hashchange as well. The alert works here but returning a string does nothing. I'm guessing that that dialog is specific to the beforeunload event.

 $(window).on('hashchange', function(){
     alert("saved?");
     return "this doesn't do anything";
 });

How should I work around this?

like image 729
user2483724 Avatar asked Oct 31 '22 19:10

user2483724


1 Answers

I think you may have to capture click event on the hashes and cancel it if not confirmed:

$('a[href^="#"]').click(function(){
    return confirm('Did you save your changes?')
});

Demo: http://jsfiddle.net/v8GbN/

like image 138
Yuriy Galanter Avatar answered Nov 12 '22 14:11

Yuriy Galanter