最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detecting if HomeEnd Keys is pressed in JS - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Aug 13, 2014 at 10:17 YoussefYoussef 3001 gold badge4 silver badges14 bronze badges 1
  • Nice. I came here at the same point in my code/testing for my infinite scroll implementation. Is the keypress event the solution that you stuck with? – Brian Layman Commented Sep 12, 2016 at 3:17
Add a comment  | 

4 Answers 4

Reset to default 9

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));
    }

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

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

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;
    }
发布评论

评论列表(0)

  1. 暂无评论