Search code examples
javascriptonunload

Struggling with onUnload


I am trying to write some javascript which asks a user, when they leave the page, if they want to fill out a survey (however annoying this may be!). I thought my solution was found by an answer on this site. This is the code I currently have that does not seem to be working:

<script language="javascript">

function comfirmsurv() {

var ConfirmStatus = confirm("We would love to receive your feedback on your experience of this page. Would you like to complete our short survey?");

if (ConfirmStatus == true) {

window.open("#");

}
else 
{window.close();} 
} 
}
window.onUnload=confirmsurv()

</script>
<body>
Test
</body>

Any help is greatly appreciated.


Solution

  • You are assigning the result of calling the function, not the function itself:

    window.onunload = confirmsurv; // Note no ()
    

    A few other issues:

    1. Javascript is case sensitive, the property you are after is "onunload", not "onUnload".
    2. The name of the function is "comfirmsurv" but you are assigning "confirmsurv"
    3. window.close() : you can only close windows you open, not others.
    4. There is an extra }.
    5. The language attribute for script elements has been deprecated for over a decade, the type attribute is required, use type="text/javascript"