Eelco Poelstra
Eelco Poelstra

Reputation: 11

jQuery keypress not working as it needs to

What I want: When I press the letter "i" the toggle will do its work.

What it does: The toggle is working on every letter pressed on the keyboard

How to fix this?

$(window).keypress(function(e) {
  e.which === 67;
  $('.metadata').slideToggle('.display-block'); 
});

Upvotes: 1

Views: 114

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You missed out the if condition, and .display-block isn't a valid parameter value for slideToggle(). Try this:

$(window).keypress(function(e) {
  if (e.which === 67) {
    $('.metadata').slideToggle(); 
  }
});

Note that keyCode 67 is B. Your question states you want to use i, so in that case you'd need to change the value to 105.

Upvotes: 2

NetVicious
NetVicious

Reputation: 4037

Use document instead of window. And you missed the IF (i think):

$(document).ready(function() {

   $(document).keypress(function(e) {
     if ( e.which === 67 ) {
        $('.metadata').slideToggle('.display-block'); 
     }
   });
});

Upvotes: 0

Related Questions