I’ve got a problem with the onunload event testing script
it must fire only on the window onunload
but it fires with load as well.. Why?
There is something wrong, and I don’t know what it is..
Please help
Here is the html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function hello(){alert("welcome to my page");}
</script>
<script type="application/javascript" src="script.js"></script>
</head>
<body onload="hello()" >
</body>
</html>
and here’s the script code
window.onunload = goodbye();
function goodbye(){
alert("Thank you for visiting.come back soon!");
}
//window.addEventListener('unload',goodbye(),false);
I’ve tried the inline calling with body tag, the window.onunload calling and the listener calling.
Nothing works correctly, and I get the “Thank you for visiting. come back soon!” message when the page first loads.
The problem is the following line:
This sets the
window.unloadevent equal to the result of thegoodbye()function, and calls thegoodbye()function immediately. Change this to:IN MORE DETAIL:
You call a function by naming it, and passing it zero or more parameters in brackets (eg:
goodbye()). When you call a function, it is called immediately, and, if it is used as part of a statement (rather than the whole statement), then ther return value of the function is used where the call was made. So, what you’re saying with the line:is: “fetch me the result of calling the
goodbyefunction, and assign the return value to thewindow.onunloadvariable”. Calling thegoodbyefunction pops up an alert, but returns null, so you are, in effect, saying, “pop up an alert right now, and then set thewindow.onunloadvariable to null”.The
window.onunloadvariable (and all other event variables) expects to be a function, so what you actually want to say here is, “set thewindow.onunloadfunction to be thegoodbyefunction, so when the system calls theonunloadevent, it will call thegoodbyefunction”, and to do that, you assign the function itself to the variable:HOWEVER
The
onunloadevent is probably not what you’re looking for. This only fires after the page has been unloaded, so most of the UI components are not available to your anymore, includingalert. Try looking intoonbeforeunloadinstead (JavaScript + onbeforeunload)