A quick overview of events in JavaScript, what they are, how they’re triggered, and how to write code that listens to events.
JavaScript events
Much of what we want to do with JavaScript is wait for users to interact
That user interaction is called an “event”
click
dblclick
contextmenu
mousedown
mouseup
mouseover
mouseout
mousemove
keypress
keydown
keyup
focus
blur
change
submit
jQuery’s on() function can be used to listen and respond
on()
There’s also off() if you want to stop listening
off()
<button id="click-me">Click me!</button>
$('#click-me').on('click', function () { alert('Hello, World!'); });
<ul> <li>Titanosaurus</li> <li>Apatosaurus</li> <li>Brontosaurus</li> <li>Brachiosaurus</li> </ul>
.is-clicked { background-color: limegreen; }
$('ul').on('click', 'li', function (e) { $(this).toggleClass('is-clicked'); });
<a class="stego-link" href="https://en.wikipedia.org/wiki/Stegosaurus">Go!</a>
var $link = $('.stego-link'); $link.on('click', function (e) { e.preventDefault(); alert($(this).attr('href')); });
<form> <label for="grocery-input">Shopping list</label> <input id="grocery-input"> <button type="submit">Add</button> </form> <ul class="list"></ul>
var $input = $('#grocery-input'); var $list = $(".list"); $('form').on('submit', function (e) { var $li = $('<li>'); e.preventDefault(); $li.html($input.val()); $list.append($li); });