-1

I'm trying to change the background colour of my div when the user presses either C, M or Y. I need to use the keypress method, but for some reason my code doesn't work.

$(document).ready(function() {
  $(document).keypress(function(event) {
    if (event === 99) {
      $(".light").css('background-color', "#00ffff");
    } else if (event === 121) {
      $(".light").css('background-color', "#00ffff");
    } else if (event === 109) {
      $(".light").css('background-color', "#00ffff");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Bobybobp
  • 95
  • 9

2 Answers2

3

You need to use event.which to determine which key was pressed. Here's working code:

$(document).ready(function() {
  $(document).keypress(function(event) {
    if (event.which === 99) {
      $(".light").css('background-color', "#00ffff");
    } else if (event.which === 121) {
      $(".light").css('background-color', "#00ffff");
    } else if (event.which === 109) {
      $(".light").css('background-color', "#00ffff");
    }
  });
});
div.light {
  width: 50px;
  height: 50px;
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>
user94559
  • 59,196
  • 6
  • 103
  • 103
0

You need to use the which value from the keypress event. I would also suggest that you use a switch-statment.

$(document).ready(function() {
  $(document).keypress(function(e) {
    var color = null;

    switch (e.which || e.keyCode || 0) { // Cover all cases
      case 99:  // Key - C
        color = '#00FFFF'; break;
      case 109: // Key - M
        color = '#FF00FF'; break;
      case 121: // Key - Y
        color = '#FFFF00'; break;
      default:
        color = '#FFFFFF';
    }

    $('.light').css('background-color', color);
  });
});
.light {
  width: 95vw;
  height: 95vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>

Thanks to smarx for the heads-up about jQuery and which.

Community
  • 1
  • 1
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Per http://stackoverflow.com/questions/4471582/javascript-keycode-vs-which, I think `which` is preferred when using jQuery. – user94559 Oct 03 '16 at 18:33