Jul 25, 2008

Asking Users To Confirm If They Wish To Leave The Page

Free Web Hosting, No Ads > CONTRIBUTE > Tutorials

free web hosting

Asking Users To Confirm If They Wish To Leave The Page

dyknight
I am sure all of us have had the frustration of having to retype an entire email from scratch because we accidentally hit "back" or otherwise left the page. As web technology improves and becomes more profound, such problems have found their simple solutions, as displayed by Google on Gmail, Google Calendars, Google Pages, Blogger etc. This tutorial will explore this script used to prevent a user from leaving the page accidentally.

In order to achieve this, make sure your users have Javascript enabled. We will be using window.onbeforeunload.

Firstly, open up your HTML in your favorite text editor, such as Notepad or Dreamweaver. You will see something like:

CODE
<html>
....
<head>
....
</head>
<body>
...
</body>
</html>


Next, paste the following into the script, between the head tags:

CODE
<script language="javascript" type="text/javascript">
window.onbeforeunload = askConfirm;
function askConfirm(){
        return "You have unsaved changes.";
        }
</script>


so that we get this:

CODE

<html>
<head>
<script language="javascript" type="text/javascript">
window.onbeforeunload = askConfirm;
function askConfirm(){
        return "You have unsaved changes.";
        }
</script>
</head>
<body>
</body>
</html>


Save the script and test it in your browser. Try navigating away from the page. A popup pane will appear, asking you to confirm your exit and showing the message: "You have unsaved changes.";
Of course, we would like to achieve more than that, such as asking only when the user has made changes to the form.

We will need to do this:

CODE
<script language="javascript" type="text/javascript">
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
    
    function askConfirm(){
        if (needToConfirm){
            return "You have unsaved changes.";
            }    
        }
</script>


We first set a boolean "needToConfirm" to false, so that we don't ask unless the user has done something, and this something will change needToConfirm to true. Before unload, the function askConfirm will be called. If the boolean "needToConfirm" is true, the function will return a string and there will be a pop-up window. Else, it will return null and the pop-up won't show. Now we need to add something to set needToConfirm to true.

CODE
<form>
    <input type="text" onchange="needToConfirm=true"/>
    <input type="submit" value="Submit"/>
</form>


The input field, when changed, will set needToConfirm to true. If unchanged, the boolean will be false. However, we do want to note that when the user has changed and SUBMITTED the form, we do not show the pop-up. So we add the following:

CODE
<form onsubmit="needToConfirm=false;">
    <input type="text" onchange="needToConfirm=true"/>
    <input type="submit" value="Submit" onclick="needToConfirm=false;" />
</form>


And we result in the final code:

CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script language="javascript" type="text/javascript">
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
    
    function askConfirm(){
        if (needToConfirm){
            return "You have unsaved changes.";
            }    
        }
</script>

</head>

<body>

<form onsubmit="needToConfirm=false;">
    <input type="text" onchange="needToConfirm=true"/>
    <input type="submit" value="Submit" onclick="needToConfirm=false;" />
</form>

</body>
</html>


There you go. You might want to save the javascript in an external file and link it, so that you don't have to enter the code on every page. Use the following:

CODE
<script language="javascript" type="text/javascript" src="[i]your file name[/i]>

 

 

 


Reply

jlhaslip
Nice code, but since it requires use of Javascript, it won't work if a user has js disabled.

Reply

Albus Dumbledore
yeah, ive seen simpler codes than this before, and as jlhaslip said, if they have Javascript disbled, it wont show anything, and sometimes that can just get soo annoying!

*closes page*
POPU-UP
Are you posative you want to leave this page?
*sighs*
*clicks yes* i said i was!!!!

hehe

Reply

SolarX
Hm, I'm using Opera and I don't have such problems, cause Opera saves the text you typed in a form or field automatically. So if you hit back accidentally and forward again nothing is lost.

But it's a good addition four IE users...

Reply

FirefoxRocks
If you read the W3Schools page, they do say that JavaScript is the scripting language on the Internet.

Opera and some extensions on the Firefox browser save form fields so they don't get cleared (well on some websites). That won't be a problem for those users.

It is a good addition for IE visitors to your site.

Reply

dyknight
Yup, Javascript is the client-side scripting language of the Internet. What I would do is to add a short notice on the frontpage to warn the user that he should have javascipt enabled. Without Javascipt, site functions and flexibility are pretty limited.

Anyway, for the more experienced, you can add more checks to ensure that you don't pop-up the window unnecessarily. For my example I added a check for submission.

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. javascript unsaved confirm - 113.18 hr back. (1)
Similar Topics

Keywords : users, confirm, leave, page

  1. How To Control Other Users’ Privileges (microsoft Windows Steadystate 2.5)
    (1)
  2. Opening Nat On Your Xbox - Upnp With Netgear
    for NETGEAR users with UPnP enabled (0)
    I think all of the NETGEAR Routers now come with UPnP Follow this tutorial and i will show you how
    to open your NAT. 1. Go to 192.168.1.1 (or 192.168.0.1 - or whatever they supplied you with) 2. Go
    down to maintenance and 'Attached Devices'. 3. My xbox is named '---' - most xboxes
    have that default name. 4. Make sure your xbox is located there and is in the IP you selected in
    your xbox wifi setup. 5. Now go down to 'Advanced' then 'UPnP' 6. If the
    'Turn UPnP On' is toggled - then uncheck it and apply. Then when it update....
  3. Dynamic Signature - Yet Another Way To Do It
    Create dynamic sigs for multiple users using .htaccess and RewriteRule (0)
    Ever since I connected a program I made in Visual Basic to MySQL database, I had an idea to create
    some sort of a status page... And I did that, where I updated my connection status every 60 seconds,
    updated my Winamp playlist, and several other interesting things... Then, I figured I could create
    an image, and display all that info, and show it on forums, as a signature... And I made a great
    PHP script, that look real fancy, and does the job perfectly... So, I was adding the reference to
    http://status.galahad.trap17.com/stat.php to all the forums... BUT (there's ....
  4. How To: Have Opera Check C-panel Webmail
    Geared toward Trap17 users (1)
    This tutorial is valid for Opera 9 or above; but previous versions might work. In the menu bar,
    go to Tools > Mail and chat accounts... Click on Add... Make sure Regular e-mail
    (POP) is selected. (It should be by default.) Click Next > . In this section, you see three
    fields: Real Name , E-mail address , and Organization . Organization is
    optional. Type in your name in the Real Name field, and your account's e-mail in the
    E-mail address field (syntax: cpanel_username@your_subdomain.trap17.com). Click Next....
  5. Showing A Users Ip Address In Php
    (5)
    In this simple tutorial I will explain how to show a users IP address in your website statistics.
    Open the file you would like to show the IP in, and insert this code where you want it to show:
    CODE <?php echo $_SERVER["REMOTE_ADDR"]; ?> An IP Address
    whould show up. If you would like to have text infront of the IP, for example, IP Address: Blah
    Blah. Type: CODE IP Address: <?php echo $_SERVER["REMOTE_ADDR"];
    ?> Make sure to save the file as '.php' format, otherwise the code will....
  6. Who's Viewing My Site?
    Targeted for AIM users (11)
    As some of you may know, I asked a question on how to get a portion of the URL in the address bar
    and save it, and thanks to several sources*, I have successfully learned how to do that. Today, I
    will share with you, step-by-step, my knowledge. The object of this tutorial is to mimic a
    feature on many subprofiles where you're able to see the AIM screennames of people who viewed
    your site. Note : The URL that I will be using extensively throughout this tutorial is
    http://yoursite.trap17.com . This is not a special URL reserved on trap17 but is merely a represe....

    1. Looking for users, confirm, leave, page

Searching Video's for users, confirm, leave, page
advertisement



Asking Users To Confirm If They Wish To Leave The Page



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE