How to go back to the previous page when clicking Esc?

Asked

Viewed 1,578 times

2

I have an item list on which when clicking on any item, and directed to another page for item details. I would like to click on the button ESC keyboard, back to previous page.

Basically make the browser navigation function by going back to the previous page, as the image below:

inserir a descrição da imagem aqui

How to go back to previous page by clicking Esc?

2 answers

3


Just you check if the pressed key was the ESC (key Code 27) and use the Window history. to return to the previous page.

See the example below:

document.onkeyup = function(e) {
  e = e || window.event; //compatibilidade com navegadores antigos IE

  if (e.keyCode == 27) {
    history.back(); //ou history.go(-1); 
  }
};

Example in Jsfiddle.

If you want to understand more about Browse History you can see more details here.

This question has some other examples of how to do what you want.

If you want to better understand how each event works, you can see this example that I took of this answer.

  • Actually, it only works if you keep the button pressed.

  • @acklay was using the wrong event, Sorry. I edited the answer

  • 2

    @Guilhermenascimento Done, thanks for the tip

  • @Is Randrade sure it’s onKeyDown? It still comes back when you keep the button down. = P

  • @acklay may be conflicting with other events, try document.onkeyup.

  • @Guilhermenascimento only worked with onKeyUp even! I had already done with window.addeventlistener("keyup") what would be the difference between addeventlistener and Document.onkeyp?

  • 2

    @acklay addeventlistener add as a "listener" event and can have multiple events, you can manage them by removing without affecting others, the . onkeyup for example can only be a single event controlled by the attribute or property. Note that in IE6/7/8 (8 with quircksmode) we used attachEvent instead of addeventlistener. One thing that addeventlistener doesn’t have up to ES5 at least and the Actionscript3.0 language does has priority, but this is another story.

Show 2 more comments

1

For your case it may be a bit over the top, but you can use the library I set up Keymap.

document.onKeyMap('esc', function(){
  // history.back(); <-- COGIGO REAL
  alert('ESC');
});
<script src="https://cdn.rawgit.com/Lautert/KeyMap/master/KeyMap.js"></script>

  • 1

    Good tip, I really liked the lib, however the most interesting of it is the key combination, I’m sure there must be some question that would fit very well as answer :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.