0

I have a button on my webpage that I needed to be triggered when the user clicks with the mouse but also when he hits the spacebar, is that even a thing?

HTML

<div class="col-12 button small-button">
       <a onclick="generator()">
            <img src="icones%20web%20projeto.png" title="Descubra um novo artista" alt="New Image">
       </a>
</div>

JS

function generator() {
    var x= Math.floor((Math.random()*35)+1);
    console.log(x);
    document.getElementById('divImage').innerHTML='<img src="img/'+x+'.png">';
 }

Khalid Ali
  • 1,224
  • 1
  • 8
  • 12
  • Hi Isabela, yep it's a thing. You'l need an `onkeydown` (or `onkeyup`) event handler in addition to your `onclick` handler. You'll then determine which key was pressed ("space" vs "enter" vs "tab") and execute the same click handler. – Jack Apr 21 '19 at 21:56
  • 1
    Even if the user doesn't have a focus on the button? I mean, imagine the focus is on another element. I'm asking this because if you have a focus on the button and press spacebar, the event click will be triggered, – Ele Apr 21 '19 at 21:57
  • 1
    @Ele, it seems (based on the provided HTML) that it's not a button in the traditional sense. Your comment does make a great point - using a button would just work. Isabela, here's a JSFiddle using a button: https://jsfiddle.net/2gxdshvt/ (which you'll see works with space) – Jack Apr 21 '19 at 22:21

1 Answers1

2

Without the use of any third-party libraries.

document.body.onkeydown = function(e){
    if (e.keyCode == 32) {
        // add your code here.
        console.log('Space pressed');
    }
}

Or using addEventListener() method:

window.addEventListener('keydown', function(e) {
    if (e.keyCode == 32) {
        // add your code here.
        console.log('Space pressed');
    }
});
Khalid Ali
  • 1,224
  • 1
  • 8
  • 12