Question

I have

<span class="cssButton"><a href="javascript:void(0);" class="buttonBlue" onclick="swfu.startUpload();"> <img src="http://uber-upload.com/img/icons/up_16.png" alt=""/> Uber-Upload! </a></span>

And i want to make it so that if you press that button, it also sets a variable that makes it so that if you try to leave the page, it will pop up one of those "Are you sure you want to leave this page" alerts to prevent people from accidently leaving while there is an upload going on.

Dont worry about unsetting the variable after the upload finishes, i'll add that, i just need one of you smart coders to make me a framework.

Thanks!

Was it helpful?

Solution

Add this declaration to the page:

var upcount = 0;

Change your onclick to:

onclick="++upcount; swfu.startUpload();"

If the swfu gives you some kind of event when it's done uploading, put this on it:

--upcount;

And add this handler:

window.onbeforeunload = function() {
    if (upcount > 0) {
        return "The upload is still in progress, leaving the page will cancel it.";
    }
}

Where browsers respect the onbeforeunload, that'll work. And most of them do, most of the time. Where they don't, well, you tried. Note that by using a counter, you're allowing for multiple uploads.

You might consider attachEvent (IE) or addEventListener (standard) (or a library like Prototype or jQuery that evens out the differences for you) for attaching your events rather than using attributes. Using attributes (aka DOM0 handlers) is fairly old-fashioned and a bit limiting (only one handler per event per element). But it does still work.

OTHER TIPS

function warnUser()
{
   if(dataIsDirty)
   {
      return "You have made changes. They will be lost if you continue.";
   }
   else
   {
      // Reset the flag to its default value.
      dataIsDirty = false;
   }
}

function isDirty()
{
   dataIsDirty = true;
}

function isClean()
{
    dataIsDirty = false;
}

Then you use it just like on the onbeforeunload event.

window.onbeforeunload = warnUser;
dataIsDirty = false; //Or true, depending on if you want it to show up even if they dont' make changes)

Then to use it, just use the 'isClean' function to anything you don't want to trigger it(Save, for instance), or you can attach 'isDirty' to any event you want to trigger it before they leave (say, editing a form field).

Relying on onbeforeunload is sketchy at best. Because spammers have abused the behavior in the same way you're suggesting the ability for people to do this has been basically removed.

You can now only respond to onbeforeunload if the close event was fired from activating a button or such.

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