need help with close tab script

Discussion in 'JavaScript' started by DjZoC, Aug 13, 2010.

  1. #1
    hello there, this is the script

    <html>
    
    <script type="text/javascript">
     var bEdited=new Boolean();
     
     function UnLoadWindow() {
      if (!(bEdited)) {
       return
      }
      return 'You are sure want to exit from this website?'
     }
     
     window.onbeforeunload = UnLoadWindow;
    </script>
    
    <body>
    
    <a href="?test=test">test</a>
    
    </body>
    </html>  
    HTML:
    this script is working but the problem is when someone click "test" link on my website all time is show that message, how i can make this to show just if the user close website (tab/browser)

    thanks for the help
     
    DjZoC, Aug 13, 2010 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    There is a number of ways that this can be solved. The quickest and easiest to explain is just to add a timer to the document.body.onclick function, so if the page exits within 2 seconds of a mouseclick the message does not show. this is how:
    
    <script type="text/javascript">
     var bEdited=new Boolean();
     bEdited = true; 
     
     function UnLoadWindow() {
     if (!(bEdited)) {
       return;
      }
      return 'Are you sure that you want to exit from this website?';
     }
     function docClick() {
        bEdited=false;
        setTimeout(function(){bEdited = true}, 2000);
     }
     document.body.onclick = docClick;
     window.onbeforeunload = UnLoadWindow;
    </script>
    
    Code (markup):
    The docClick function assigns a value of false to the variable bEdited, so if the page exits the message does not show. It then sets a timer for the value to be set back to true in 2 seconds.
     
    camjohnson95, Aug 15, 2010 IP