简体   繁体   中英

I Need a way to execute a particular function when i press the forward key or the back key in javascript

I need a way to execute a particular function when I press the forward key or the back key in javascript. So that it may work when the forward button is pressed it may execute the function but it should work without taking the input in any type of text box.

I mean it should work on the whole page no matter where I am on the page but if I press the forward button the function should be executed.

I know how to do it by taking an input in a text box by matching the key codes but don't know how to make it work in someway else.

If by forward and back keys you mean the arrow keys, this is how you can do it!

document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
    case 37: // left
    break;

    case 38: // up
    break;

    case 39: // right
    break;

    case 40: // down
    break;

    default: return; // exit this handler for other keys
}
   e.preventDefault(); // prevent the default action
});

I feel pretty confident with my assumption that you are referring to the arrow keys on the keyboard. And as you say you already have working code for when a textbox is focused, I also assume you are using onkeydown (or one of the similar ones) already. So the solution is to add the event listener to the document instead.

Like this for example:

document.onkeydown = function(e){
    // Your existing code goes here.
}

You need to use onkeydown if you want to detect arrow keys.

Here is a working example

Use onkeydown as this should work for all browsers. I don't think onkeypress will work with google chrome for the arrow key events.

  • 38 = Up Arrow
  • 40 = Down Arrow

To find more you can use console.log(event.keyCode); in your onkeydown function to log the key codes to your browsers console.

 function MyFunc() { alert("Key up or down!"); } document.onkeydown = function() { if (event.keyCode == 38 || event.keyCode == 40) { MyFunc(); } }

If you have any questions please leave a comment below and I will get back to you as soon as possible.

I hope this helps. Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM