Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery prevent window closing

Tags:

I want to ask user whether he really want to leave the page or not, when he clicks the close button just like it done in google docs. How to do that using jquery?

like image 888
Vetragon Avatar asked Oct 14 '09 09:10

Vetragon


People also ask

How do I stop closing a tab?

To do that open Prevent Close, and then right-click the tab with your mouse. From the context menu select Pin tab. After doing that, the tab will shrink down to a different size from the rest of the tabs. Next, just mark it with your mouse and drag the tab to the far left of your browser's tab lineup.

How to get window close event in JavaScript?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

What is window close in JavaScript?

JavaScript provides an in-built function named close() to close the browser window that is opened by using window. open() method.


2 Answers

You set the window's onbeforeunload property to a function.

This post has a good example on how to do it.

Or another example:

<script language="JavaScript">   var needToConfirm = true;    window.onbeforeunload = confirmExit;   function confirmExit()   {     if (needToConfirm)       //return message to display in dialog box;   } </script>  ...  <input type="Submit" value="Save" onclick="needToConfirm = false;" /> 


And to set needToConfirm for your form you can:

$(document).ready(function() {      $(':input', document.myForm).bind("change", function() { needToConfirm = true; }); // Prevent accidental navigation away }); 
like image 153
Prody Avatar answered Sep 20 '22 13:09

Prody


Following worked for me;

 $(window).unload(function() {                 if(event.clientY < 0) {                     //do whatever you want when closing the window..                 }             }); 
like image 32
Dilhan Jayathilaka Avatar answered Sep 19 '22 13:09

Dilhan Jayathilaka