Jump to content

onUnload="" function does not seem to work


justin7410

Recommended Posts

hey guys,

 

so i am messing around with some simple JS, and i was using the onLoad & onUnload handlers.

 

 

 

i can easily get the onLoad=(function) to work properly, yet when it comes to getting the onUnload to work when i close the window or refresh the site, noting seems to work

<script>

function alert1(){
    alert("Welcome to the page, enjoy");
}
function aler02(){
    alert("Thanks for visiting, goodbye");
}
</script>
<body onLoad="alert01();" onUnload="alert02();">

     <p> This is text </p>
</body>

again when i open the site, it works just fine and as expected. when i close or refresh i expect an alert to let me know i am leaving, yet nothing.

 

any suggestions ?

 

 

 

Link to comment
Share on other sites

You don't register the handler on the <body> element but on the window object.

 

window.onbeforeunload = function(){ if(confirm("Are you sure you want to leave this page?")) return false; else return true; };

 

Hey man, thanks for the great help, but tell something. What is the window object ? and why is it i have to do this instead of putting it directly on the body tag as i was doing ? if that was the case then wouldnt the onLoad element face the same issue ?

Link to comment
Share on other sites

The window object is the global object in client-side JavaScript.

 

All top-level variables (variables declared in the highest scope JavaScript has) are automatically properties of the global object.

 

window also refers to the web browser's window itself and also has properties that reveal the current site's URL and some others.

 

However, you are mistaking something in your assumption made above; the onload attribute of the body tag is fired when the body tag has completely loaded.

But because you want to fire the next event when the web browser - not the body tag! - is about to be "unloaded", you register the event handlers on the window object, not on a DOM object (which represents <body onload=""> with document.body.onload, rather than window.onload).

 

Hope this explains this a little.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.