Nov 21, 2009
Pages: 1, 2

Asking Users To Confirm If They Wish To Leave The Page

free web hosting
Open Discussion > MODERATED AREA > Tutorials

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]>

 

 

 


Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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...

Comment/Reply (w/o sign-up)

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.

Comment/Reply (w/o sign-up)

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.

Comment/Reply (w/o sign-up)

(G)Mario Herak
Nice work, nice code!
Asking Users To Confirm If They Wish To Leave The Page

Thank you for great script. Itīs quite easy and simple, but works great! I hope it helps me with my eshop to ask my customers why (if itīs true) they havenīt bought something.

-reply by Mario Herak

 


Comment/Reply (w/o sign-up)

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

Ive been looking for a non-Javascript code but still not found one. When I first looked at it, it didn't look like js but it does now.

Comment/Reply (w/o sign-up)

damoon
javasript is too irrational.....i love PHP better but thanks anyways

Comment/Reply (w/o sign-up)

mahesh2k
QUOTE
javasript is too irrational.....i love PHP better but thanks anyways


Javascript is irrational ? ? excl.gif How is that ? Javascript and PHP is comparable ? I don't think so.



Comment/Reply (w/o sign-up)



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*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Pages: 1, 2
Similar Topics

Keywords : users, confirm, leave, page

  1. Deny Or Grant Users Access To Files Of Choice (vista)
    Uses Bat Files To Deny Or Grant People Access To Files (3)
  2. How To Control Other Users’ Privileges (microsoft Windows Steadystate 2.5)
    (1)
    Recently Microsoft has developed a program that makes user control easier. The program is called
    Windows SteadyState 2.5 and it needs a genuine version of windows. System Requirements
    • Supported Operating Systems: Windows Vista Enterprise; Windows Vista Home Premium; Windows
    Vista Ultimate Windows XP Professional, Windows XP Home Edition, Windows XP Tablet PC Edition with
    Windows XP Service Pack 2 (SP2) installed or Service Pack 3 (SP3) installed, Windows Vista Business,
    Windows Vista Home Basic, Windows Vista Starter, or Windows Vista with Servi....
  3. Opening Nat On Your Xbox - Upnp With Netgear
    for NETGEAR users with UPnP enabled (1)
    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....
  4. 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 ....
  5. 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....
  6. 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 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: Make sure to save the file as
    '.php' format, otherwise the code will not work.....
  7. 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
See Also,
advertisement


Asking Users To Confirm If They Wish To Leave The Page

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com