UX Design and Development course

Keyboard events


Mouse events are pretty common. click is just one of them. Keyboard events on the other hand offer up different kinds of interactions, .keydown(), .keypress() and .keyup().

Our HTML is:

<div class="cost">
  <p>total: <span id="total">$0.00</span></p>

To make this work, we will hook off the .cost class on the div. Using the .on() method again I am going to use the keyup event listener on the input with the class of qty.

To set our var price, I need to find the .closest ancestor with the .cost class by transversing up the DOM. Using the .data() method, I can then grab the string from the data-price attribute.

To set the qty var, I need to grab this value by using the .val() method.

Last, using #total and the text() method and can then multiply the price by qty and have that update in the DOM.

Also note, to convert the var statement from a string into a number, adding the + character before the object will convert the string to a number.

Also note that we are using $(this) as this is not a jQuery object yet.

$('.cost').on('keyup', '.qty', function() {
  var price = +$(this).closest('.cost').data('price');
  var qty = +$(this).val();
  $('#total').text('$' + price * qty);

Interesting, I am using .text() for the price? Yes, you can use this function to pass in either a character string or numbers.

Play with code

JS Bin

Can we build something else?

This exercise gets me thinking. Can we build a simple calculator? Sure we can. First we need some HTML:

<div class="calc">
  <span>+</span> <span>=</span><span id="sum">0</span>

Our jQuery is going to look pretty similar to the previous example. Basically on the .keyup() event I am targeting the .numTwo element within the .calc block.

Create some variables using the .val() method pulling the strings from input fields.

Last, I add the values together and bind this to the #sum via the .text() method. And SNAP, a simple jQuery calculator.

$('.calc').on('keyup', '.numTwo', function() {
  var numOne = +$('.num').val();
  var numTwo = +$('.numTwo').val();
  $('#sum').text(numOne + numTwo);