title: JavaScript before leaving the page
body: <p>I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  function con() {
      var answer = confirm("do you want to check our other products")
      if (answer){
  
          alert("bye");
      }
      else{
          window.location = "http://www.example.com";
      }
  }
  &lt;/script&gt;
  &lt;/head&gt;
  
  &lt;body onunload="con();"&gt;
  &lt;h1 style="text-align:center"&gt;main page&lt;/h1&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>But it confirm after page already closed? How to do it properly?</p>
  
  <p>It would be even better if someone shows how to do it with jQuery?</p>