Solved

Fire function before close

Posted on 2008-10-29
1
2,327 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 16

Accepted Solution

by:
sh0e earned 500 total points
ID: 22837536
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
This article discusses how to implement server side field validation and display customized error messages to the client.
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…
Suggested Courses

630 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