JavaScript
Summary - Events
Build a shortcut entry app using click and keydown events.
Summary - Events
In this group you learned the basics of events: adding listeners with addEventListener, reacting to clicks with click, tracking the mouse with mouseover and mouseout, capturing keys with keydown, and using the target and type properties of the event object.
Now let us combine them: when the user types a shortcut in an input and presses Enter, or clicks the Add button, the shortcut is added to a list. First we will write the addShortcut function, then wire it up with two listeners.
Exercise Write the addShortcut function
Define a function named addShortcut. Inside it, select the input with document.querySelector('#shortcut-input'); create a new list item with document.createElement('li'); assign the input's value to its textContent; call classList.add('shortcut'); finally call appendChild on document.querySelector('#shortcut-list') to add the item to the list.
Show example solution
function addShortcut() {
const input = document.querySelector('#shortcut-input');
const item = document.createElement('li');
item.textContent = input.value;
item.classList.add('shortcut');
document.querySelector('#shortcut-list').appendChild(item);
input.value = '';
}
Exercise Wire up the listeners
Select the button with document.querySelector('#add-button') and the input with document.querySelector('#shortcut-input'). Add an arrow function handler to the button with addEventListener('click', ...) that calls addShortcut(). Add a handler to the input with addEventListener('keydown', ...); the handler parameter should be event, and when event.key === 'Enter' it should call addShortcut().
Show example solution
const addButton = document.querySelector('#add-button');
const input = document.querySelector('#shortcut-input');
addButton.addEventListener('click', () => {
addShortcut();
});
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
addShortcut();
}
});
Test yourself
-
Match the group concepts
- addEventListener
- Adds event listener
- click
- Click event
- keydown
- Key press
- event.target
- Clicked element
-
Check for the Enter key
input.addEventListener('keydown', (event) => {
if (event.key === '____') {
addShortcut();
}
});
Show answer
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
addShortcut();
}
});
Next lesson: Event bubbling