Youssef
Youssef

Reputation: 300

Detecting if Home/End Keys is pressed in JS

I am trying to implement an infinite scroll in JS, I am using $(window).scroll() to detect the scroll position, every thing is working fine, I just have one issue I want the url to change if the user clicks the 'Home' key and then change again if the user press the 'End' key.

So when Home is clicked the scroll position will be move to the top and when End is clicked the scroll position will be moved to the bottom.

My Question is, how do you detect these behaviors (pressing Home/End)?

Youssef

Upvotes: 2

Views: 7209

Answers (4)

Scott Wager
Scott Wager

Reputation: 868

In an onkeydown callback, check for e.key === 'Home' and e.key === 'End'

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values

Upvotes: 4

Alex Joe
Alex Joe

Reputation: 389

Home, PageUp, PageDown, End and some other keys are only triggered by onkeydown, not onkeypress see this post

Upvotes: 5

Abhishek Sharma
Abhishek Sharma

Reputation: 281

its simple to detect please look at following code :

<input type="text" id="txtKey" onkeyup="keyPressEvent(event)" />

   function keyPressEvent(e) {


        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 35) {
            alert('end key press');
        }
        if (code == 36) {
            alert('home key press');
        }
        return false;
    }

Upvotes: 2

Joakim M
Joakim M

Reputation: 1803

KeyCode is 35 for END 36 for HOME!

  function myKeyPress(e){

        var keynum;

        if(window.event){ // IE                 
            keynum = e.keyCode;
        }else
            if(e.which){ // Netscape/Firefox/Opera                  
                keynum = e.which;
             }
        alert(String.fromCharCode(keynum));
    }

Upvotes: 9

Related Questions