JavaScript events

A quick overview of events in JavaScript, what they are, how they’re triggered, and how to write code that listens to events.

Go fullscreen: ⌃⌥F

JavaScript events

It’s all eventful

Much of what we want to do with JavaScript is wait for users to interact

That user interaction is called an “event”

Event listening

  1. When a user interacts with your website an event is triggered
  2. Your JS can listen to when that event happens
  3. A function you write can be called when an event happens

Events

  • click, dblclick, contextmenu
  • mousedown, mouseup, mouseover, mouseout, mousemove
  • keypress, keydown, keyup
  • focus, blur, change, submit
  • animation, transition, touch, drag, browser
  • and many, many more…

Responding to events

jQuery’s on() function can be used to listen and respond

There’s also off() if you want to stop listening

HTML
<button id="click-me">Click me!</button>
JavaScript
$('#click-me').on('click', function () {
  alert('Hello, World!');
});
HTML
<ul>
  <li>Titanosaurus</li>
  <li>Apatosaurus</li>
  <li>Brontosaurus</li>
  <li>Brachiosaurus</li>
</ul>
CSS
.is-clicked {
  background-color: limegreen;
}
JavaScript
$('ul').on('click', 'li', function (e) {
  $(this).toggleClass('is-clicked');
});
HTML
<a class="stego-link" href="https://en.wikipedia.org/wiki/Stegosaurus">Go!</a>
JavaScript
var $link = $('.stego-link');

$link.on('click', function (e) {
  e.preventDefault();
  alert($(this).attr('href'));
});
HTML
<form>
  <label for="grocery-input">Shopping list</label>
  <input id="grocery-input">
  <button type="submit">Add</button>
</form>
<ul class="list"></ul>
JavaScript
var $input = $('#grocery-input');
var $list = $(".list");

$('form').on('submit', function (e) {
  var $li = $('<li>');
  e.preventDefault();
  $li.html($input.val());
  $list.append($li);
});
Start

JavaScript events

A quick overview of events in JavaScript, what they are, how they’re triggered, and how to write code that listens to events.