Solved

Fire function before close

Posted on 2008-10-29
1
2,250 Views
Last Modified: 2012-05-05
I'm trying to get some javascript to run before the user closes the form, and I'm using onbeforeunload, but it's firing on postbacks, in addition to when the form closes.  

Is there a way to get this script to only fire when the form is about to be closed.
0
Comment
Question by:ARACK04
1 Comment
 
LVL 16

Accepted Solution

by:
sh0e earned 500 total points
Comment Utility
Not really.  You can check for window.event.clientY < 0.  This will still catch the X button.  

However, if you simply want to warn the user that they will lose data if they close the window, it may be better to use a flag that determines if there is data that has been changed.
Or, what you can do, is whenever you postback or navigate or anything else you don't want it to fire, you set a flag that prevents the confirmation from popping up.

<a href="http://google.com" onclick="flag=false;">link 1</a>

<form onsubmit="flag=false;">

<input type="submit"></input>

</form>
 

<script>

flag=true;

window.onbeforeunload = function(){if(flag)return "are you sure?";};

</script>

Open in new window

0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now