1

I am creating a HTML layout where user can fill the data and save that page in HTML and JSON formats by using "save" and "save as draft" resp. Can i use

window.onbeforeunload

twice in my template.html file to show two different alert messages?

The alerts would show:

  • when page is empty and user tries to go to load another page
  • when user fills the data in the layout and tries to leave the layout without saving
sachleen
  • 30,730
  • 8
  • 78
  • 73
mdp
  • 815
  • 4
  • 17
  • 32
  • 3
    I'm not sure what you mean by use it twice: onbeforeunload should be a function, so why not just had a conditional statement in the function to determine which message to show? – phenomnomnominal Jun 15 '12 at 23:22
  • Check out this answer for more general info on javascript event binding and the various methods used to do so: http://stackoverflow.com/questions/6902033/element-onload-vs-element-addeventlistenerload-callbak-false/6902073#6902073 – Chris Baker Jun 15 '12 at 23:58

2 Answers2

1

At first see this example to to understand what will happen if you use it twice, then the idea given bellow

window.onbeforeunload=function()
{ 
    if(form_empty())
        return "Form is empty"; // message for empty form 
    else
        return "Form is not empty"; // message for filled up form 
}

function form_empty()
{
    // check form fields whether the form is empty or not
    // return true if form is empty
    // return false if form is not empty
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

Just like any other event handler assigned in this way, if you set it again it will destroy any handler that was already there.

Now, if you're adding and removing the event based on the state of the page, then that shouldn't be a problem. Otherwise, it's a bit more complicated. In the case of onbeforeunload, however, it would be best to just have one.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592