Melissa
Melissa

Reputation: 787

Execute JS code after pressing the spacebar

this is my code in JavaScript:

var changeIdValue =  function(id, value) {
document.getElementById(id).style.height = value;
};

document.getElementById ("balklongwaarde").addEventListener("click", function(){ changeIdValue("balklongwaarde", "60px")});

document.getElementById ("balklevensverwachting").addEventListener("click", function(){ changeIdValue("balklevensverwachting", "60px")});

document.getElementById ("balkhart").addEventListener("click", function(){ changeIdValue("balkhart", "60px")});

document.getElementById ("balklever").addEventListener("click", function(){ changeIdValue("balklever", "60px")});

document.getElementById("balkhersenen").addEventListener("click", function(){ changeIdValue("balkhersenen", "60px")});

I want to execute this code after press on keyup....

Has anyone an idea how?

Upvotes: 59

Views: 195520

Answers (5)

nicael
nicael

Reputation: 18995

There're couple of ways to do this. I am also including a deprecated one with keyCode (from the original answer) just in case (it still seems to work actually as of 2023).

document.body.onkeyup = function(e) {
  if (e.key == " " ||
      e.code == "Space" ||      
      e.keyCode == 32      
  ) {
    //your code
  }
}

BONUS: I've made a quick snippet to get key, code and keyCode for any character.

Usage: 1) type in any letter 2) profit!

Pro tip: you could also run a snippet in different browsers to have fallbacks just in case.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="text" placeholder="enter a char here" id="char-finder"><p class="key"> <pr>key</pr> for <pr class="char">space</pr> is <pr class="tr">&nbsp;</pr></p><p class="code"> <pr>code</pr> for <pr class="char">space</pr> is <pr class="tr">Space</pr></p><p class="keycode"> <pr>keyCode</pr> for <pr class="char">space</pr> is <pr class="tr">32</pr></p><script>document.getElementById('char-finder').onkeyup=function(e){key=e.key==" " ? "&nbsp;" : e.key; code=e.code; kcode=e.keyCode; char=e.key==" " ? "space" : e.key; $(".key .tr").html(key); $(".code .tr").html(code); $(".keycode .tr").html(kcode); $(".char").html(char);}</script><style>body{font-size: 17px;}input{border: 1px solid grey; border-radius: 10px; font-size: 15px; padding: 5px;}pr{font-family: Menlo; padding: 3px; border-radius: 5px; font-size: 15px; display: inline-flex; justify-content: center; background: rgb(230, 230, 230); min-width: 20px;}.key pr:first-child{background: rgb(0, 230, 230);}.keycode pr:first-child{background: rgb(230, 0, 50); color: white;}.code pr:first-child{background: rgb(230, 230, 0);}pr.tr{margin-left: 5px; border: 1px solid black; background:transparent;}</style>

Upvotes: 135

neiya
neiya

Reputation: 3142

keyCode is deprecated. You could use key (the character generated by pressing the key) or code (physical key on the keyboard) instead. Using one or another can have different outputs depending on the keyboard layout.

document.addEventListener('keydown', (e) => {
    if (e.code === "Space") {
        // Do your thing
    }
});

or

document.addEventListener('keydown', (e) => 
    if (e.key === " ") {
        // Do your thing
    }
});

Upvotes: 7

user670839
user670839

Reputation:

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

Upvotes: 32

Ronnie Smith
Ronnie Smith

Reputation: 18575

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

Upvotes: 4

NNR
NNR

Reputation: 303

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

    }
});

Upvotes: 11

Related Questions