Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Fire function before close

Posted on 2008-10-29
1
Medium Priority
?
2,362 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 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
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…

916 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