0

I am trying to select the div with class of keys when the respective key is pressed on the keyboard.

I have tried both with JavaScript and jQuery but its not working and shows a null output.

How do i select the div of a particular data-attribute when the key is pressed?

Please see the code below:

html

<div class="row-2">
    <div data-key="65" class="keys">
      <kbd>A</kbd>
    </div>
</div>

Js

    window.addEventListener('keydown',function(e){
      const here = document.querySelector('.keys[data-key="${e.keycode}"]');
      console.log(here);     
      });

Jquery

    $(document).ready(function(){
       $('html').on('keydown',function(event){
       var press = event.which;
       console.log(press);
       console.log(document.querySelector('.keys[data-key="${press}"]'));
       });

});

3 Answers 3

1

You're almost there! Just use the attribute selector with the value of press to get to the desired element.

The following demo highlights the key which was pressed.

$(document).ready(function() {
  $('html').on('keydown', function(event) {
    var press = event.which;
    $(`div[data-key=${press}]`).addClass('highlight');
  });
});
.highlight {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row-2">
  <div data-key="65" class="keys">
    <kbd>A</kbd>
  </div>
  <div data-key="66" class="keys">
    <kbd>B</kbd>
  </div>
  <div data-key="67" class="keys">
    <kbd>C</kbd>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

You are using the wrong string literal for your interpolation:

'.keys[data-key="${e.keycode}"]' should be `.keys[data-key="${e.keycode}"]`

Comments

0

Just change this .keys[data-key="${press}"] for this .keys[data-key="' + press + '"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.