简体   繁体   中英

Why does my keypress handler not work when I use anchors

I use jQuery for my homepage and add a keylistener when the window is loaded. It looks like this:

$(window).load(function(){
    var debug = $('#debug'); // this is a fixed div I use to print debug
                             // information to the screen
    $(window).keypress(function(event) {
        var keyCode = event.keyCode ? event.keyCode : event.which;
        debug.text(keyCode);
        if (keyCode == 106 || keyCode == 40)
            nextCard();
        else if (keyCode == 38 || keyCode == 107)
            prevCard();
    });
});

You can jump from one card to another using the arrow up and arrow down key or 'j' and 'k'. It works fine as long the page is loaded without jumping to an anchor. That means when I go to the page like http://www.blah.com it works fine but when I load it like this http://www.blah.com#anchor it doesn't work anymore.

Update: $(window).load() gets fired, so this is not the problem.

Do you have any ideas what the problem could be? Thanks!

If you cant find an easy solution, you could try to rebind your function everytime when the hash changes. For example with this plugin http://benalman.com/projects/jquery-hashchange-plugin/

I found the problem. It actually had nothing to do with the keypress handler. It was a handler that initiates a scrolling animation whenever someone enters the page with a hash in the URL.

Nevertheless thanks for making me think about my code :P next time I try to consider such bugs before I post here....

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