ES6 Event Listeners

🌱 Created: 11/11/2021

✏️ Updated: 31/07/2022

Author: Dante Mogrim


Click

HTML:

<div style="width: 200px; height: 200px; background-color: cornflowerblue">
    <p style="color: white">Click somewhere in this square.</p>
</div>

JavaScript:

const div = document.querySelector('div');

div.addEventListener('click', () => {
    console.log('Somebody clicked me!');
});

Focus

HTML:

<input placeholder="Tab into me." />

JavaScript:

const input = document.querySelector('input');

input.addEventListener('focus', () => {
    console.log('The input field has been focused!');
});

Keypress

HTML:

<p>Press any key while focused on this window.</p>

JavaScript:

window.addEventListener('keypress', () => {
  console.log('Someone pressed a key!');
});

Media

HTML:

<video
    width="640"
    height="480"
    src="https://ia903406.us.archive.org/29/items/BannedCartoonsTransLuxFelixTheCatKingOfTheMoonVeryGood/Banned%20Cartoons%20-%20Trans-Lux%20-%20Felix%20The%20Cat%20-%20King%20Of%20The%20Moon%20-%20Very%20Good.mp4"
    controls
    >
</video>

JavaScript:

const video = document.querySelector('video');

video.addEventListener('play', () => {
  console.log('Felix the Cat is now playing!')
});

video.addEventListener('pause', () => {
  console.log('The episode is now paused.')
});

Window

HTML:

<div style="height: 200vh; background-color: pink"></div>

JavaScript:

window.addEventListener('scroll', () => {
  console.log("Chocolate starfish! Keep on scrollin' bebbeh!");
});