Execute JS code after pressing the spacebar

不羁岁月 提交于 2019-11-28 13:17:51
document.body.onkeyup = function(e){
    if(e.keyCode == 32){
        //your code
    }
}

This will be executed after you hit spacebar.

JSFiddle.

In JQuery events are normalised under which event property.

You can find any key value here eg:spacebar value(32).

This function may help you.

$(window).keypress(function(e) {
    if (e.which === 32) {

        //Your code goes here

    }
});

document.activeElement is whatever element has focus. You'll often find both spacebar and enter firing click on the focused element.

document.body.onkeyup = function(e){
    if(e.keyCode == 32 || e.keyCode == 13){
        //spacebar or enter clicks focused element
        try {
            doc.activeElement.click();
        }
        catch (e) {
            console.log(e);
        }            
    }
};  

Then the CSS might be:

.focusable-thing:hover {
    cursor: pointer;
}
.focusable-thing:focus {
    -webkit-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
    -moz-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
    box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
}

The 2019 version of this would be: (works in all major browsers - Chrome, Firefox, Safari)

Spec link - https://www.w3.org/TR/uievents/#dom-keyboardevent-code

code holds a string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. The un-initialized value of this attribute MUST be "" (the empty string).

// event = keyup or keydown
document.addEventListener('keyup', (event) => {
  if (event.code === 'Space') {
    console.log('Space pressed')
  }
})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!