user1571012
user1571012

Reputation: 133

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.

Upvotes: 3

Views: 448

Answers (2)

RobG
RobG

Reputation: 147403

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"

Upvotes: 4

Jay
Jay

Reputation: 4686

The unload property is incorrectly stated as onUnload instead of onunload. Also, the code have too many errors here and there.

The browser's console log provides a log that you can use to find the cause of error.

Here's the fixed script.

<SCRIPT>
function confirmsurv() {

  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>

Upvotes: 0

Related Questions