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
Solved

Detecting when user hits "Backspace" or navigates to previous page

Posted on 2008-10-23
15
1,296 Views
Last Modified: 2010-05-18
How do I do this in JavaScript:

Detect when user hits "Backspace" or navigates to previous page?

Can I trap keypresses in JavaScript?  Or what is the best approach for this?
0
Comment
Question by:knowlton
  • 5
  • 5
  • 3
  • +2
15 Comments
 
LVL 19

Assisted Solution

by:bevhost
bevhost earned 50 total points
ID: 22791812
0
 
LVL 8

Expert Comment

by:mkosbie
ID: 22792044
Regarding pressing the back button/navigating from your page, see this other Q in progress (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_23843168.html).  Specifically to capture the keypress, you want to use the onkeypress/onkeydown/onkeyup events.  Something like the attached code:
var BACKSPACE = 8;
 
window.onkeyup = function(e) {
    if(!e) e = window.event;
 
    var key = e.keyCode ? e.keyCode : e.which;
    if(key == BACKSPACE) yourBackspaceFunction();
};

Open in new window

0
 
LVL 44

Expert Comment

by:scrathcyboy
ID: 22792340
that doesn't detect a mouse click on the back button, or a hot key customized by the user to go back.  In short, the answer to your question, I believe, is that YOU CANNOT DETECT THIS !!
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

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

 
LVL 8

Expert Comment

by:mkosbie
ID: 22792595
As explained in the Q I referenced in my original answer, you can handle the window.onbeforeunload event.  That event fires when your page is closed for ANY reason.  See the Q for a further explanation.
0
 
LVL 5

Author Comment

by:knowlton
ID: 22796742
There may be more than one way to skin a cat here.

I think what I need (on the page in question) is to know what page I just came from.  Then I need to detect when I go back to that page, and (perhaps) if the Backspace key was what instigated the "go back" action.

Then when I go back to the page I just came from, depending on the page, I need to tell that page that I am coming FROM the page I just came from.


What I am driving at is this.  I have a page that displays some search results.  Each search result has a hyperlink that takes me to another page.  On the other page, when I click "go back" or press the Backspace key or do any action that takes me back to the page I came from -- I need to know.
0
 
LVL 8

Expert Comment

by:mkosbie
ID: 22798825
Generally, you would use the document.referrer property to accomplish this.  The problem is, when you go back in a browser, the referrer isn't reset to the page you're coming back from, it's left at it's value when the page you go back to was first loaded.  That makes it pretty useless in this case.

Also, because as we discussed, there's no effective way to know when a user goes back on a page (as opposed to closing it, going to a different page, etc), you won't be able to trap the back event either.

You might be able to put together a solution as follows:
   1) Disable caching of your search results page (to prevent going back)
   2) Provide your own "Back to results" link on all result pages
   3) Put special code on the links to tell the previous page where you're coming from
0
 
LVL 44

Expert Comment

by:scrathcyboy
ID: 22799211
that's a totally different consideration than using the back button, which you cannot control.  Getting the page you came from is as simple as doing this --

in javascript --

function GetPrevPage()  {
if (document.referrer&&document.referrer!="") {
  var prevPage= document.referrer;
  document.getElelmentById('backlink').href=prevPage;
  }
}

in HTML

<A href=" " > click here to go back</A>

So you can put that function call in an onClick, or maybe better --

<BODY  onLaod="getPrevPage();" >

that way the previous page link is set every time you load a page.

You can also use onbeforeunload(), which activates when you leave a page.


0
 
LVL 44

Assisted Solution

by:scrathcyboy
scrathcyboy earned 150 total points
ID: 22799219
sorry, the link has to have the right ID --  <A href=" " id="backlink"> click here to go back</A>
0
 
LVL 5

Author Comment

by:knowlton
ID: 22814949
Going back to the keypress approach.

I can detect regular keypresses like "t" or "w" but the backspace key does not fire:

function HandleBackButton(current) {
              e = window.event;
              var key = e.keyCode;
              alert(key);  // Does not work with "Backspace" keypress
}
0
 
LVL 8

Accepted Solution

by:
mkosbie earned 300 total points
ID: 22816400
In IE, it's not ever firing the keypress or keyup events for a backspace.  It does fire the keydown event though.  FYI, in the HandleBackspace function, if you don't have the line return false, the page will still go back.  If you want the page to go back, use return true.  Try this:
var BACKSPACE = 8;
document.onkeydown = function(e) {
	if(!e) e = window.event;
	var key = e.keyCode ? e.keyCode : e.which;
	if(key == BACKSPACE) return HandleBackspace();
};
 
function HandleBackspace() {
	alert("Backspace clicked!");
	return false;
}

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
ID: 22816673
I need to check if the focus is on a control like a textbox or radiobutton when backspace is pressed.

For example ...  in a textbox a backspace should erase to the left ... not invoke "previous page in history"
0
 
LVL 5

Author Comment

by:knowlton
ID: 22822532
This seems to do the trick (see snippet):
	// function to possibly override keypress
  	trapfunction = function(event) {
  		var keynum;
 
  		if (window.event) // eg. IE
  		{
  			keynum = window.event.keyCode;
  		}
  		else if (event.which) // eg. Firefox
  		{
  			keynum = event.which;
  		}
 
  		// backspace has code 8
  		if (keynum == 8) {
  			if ((document.activeElement.getAttribute("type") === "text") | (document.activeElement.getAttribute("type") === "textarea")) {
  				return true;
  			}
  			else {
  				__doPostBack('', 'BACKSPACE');
  			} 			
  		}
 
  		return true;
 
 
	document.onkeydown = trapfunction; // IE, Firefox, Safari
	document.onkeypress = trapfunction; // only Opera needs the backspace nullifying in onkeypress
  

Open in new window

0
 
LVL 5

Author Comment

by:knowlton
ID: 22822547
Can we split the points among the participants?
0
 
LVL 8

Expert Comment

by:mkosbie
ID: 22825867
0
 
LVL 1

Expert Comment

by:Vee_Mod
ID: 22833880
Stopping auto-close by Asker request.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone 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

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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…

766 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