user2483724
user2483724

Reputation: 2119

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?

Upvotes: 6

Views: 1743

Answers (1)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

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/

Upvotes: 2

Related Questions