logo
logo

Course Overview

Introduction

Types

Basic Types

Simple Arithmetic

Fahrenheit to Celcius

Absolute Value

Is Even

Objects

Access Nested Object

Add Method to Object

Rectangle Area

Arrays

Add Element

Filtering Arrays

Remove First Element

Find Largest Number

Concatenate Arrays

Reverse String

Find Index

Types Cheatsheet

Types Quiz

Variables

Intro to variables

Variables Continued

Is String or Number

Variable Scope

Variables Quiz

Variables Cheatsheet

Statements & Operators

Conditionals

Nested Conditionals

Switch Statements

Conditionals Quiz

Compare Numbers

Loan Eligibility Checker

Leap Year Checker

Conditionals Cheatsheet

Functions

Intro to Functions

Rest and Spread Parameters

Sum All

Merge Arrays

Arrow Functions

Double Values

Count Occurrence

Calculator

Make Sandwich

Find Arbitrary Max

Execution Context

Context with Call

Context with Apply

Functions

Functions Cheatsheet

Loops

While Loops

Countdown

Sum of Odd Numbers

Sum of a Range

For Loops

Looped Sum

Count Characters

Find Max

Reverse String

Count Occurrences

Find Average

ES6 Loops

Sum Array

Filter Even Numbers using filter()

Find Maximum Number using reduce()

Find First Even Number using find()

Find Index of First Negative Number using findIndex()

Check If Any Object Has a Certain Property using some()

Check If All Values are Strings using every()

Loops

Loops Cheatsheet

The DOM

Intro to DOM

getElementById

DOM Query Selectors

Getting and Setting ID and Class

Appending and Removing Elements

Append Element

DOM Traversal

Get Tag Count

Style Elements

Toggle Class

Change ID and Class Names

Apply Styles to Class

Create Table

Create List

The DOM

DOM Cheatsheet

Events

Intro to Events

Event Propagation

Listen for Click

Log Event Type

Stop Listening for Click

Prevent Spacebar

Basic Debounce

Click Counter

Resize Logger

Events

Events Cheatsheet

Template Literals

Template Literals

Template Literals Part 2

Format URL

Email Message

Formatted Date

Template Literals

Template Literals Cheatsheet

Destructuring

Destructuring Arrays

First 2 Sum

Remove First Two

Destructuring Objects

Destructuring Nested Objects

Default to New York

Destructure Rest

Log Person Details

Log Name

First Names

Destructuring

Destructuring Cheatsheet

Exceptions

Throw Exceptions

Array Length

Get Random Element

Try Catch Blocks

Throw Custom Error

Custom Exception Constructor

Exceptions

Exceptions Cheatsheet

Object Oriented Programming

OOP in Javascript

Constructors and Inheritors

Crypto Coin Constructor

Crypto Portfolio

Object Oriented JS

Introduction to Classes

Crypto Coin Class

Static Methods

Crypto Validator

Grouping Classes

Create a Digital Wallet

Altcoin Inheritance

Classes

Object Oriented Programming Cheatsheet

Callbacks & Promises

Callbacks

Promises

Find Crypto by Name

Promises Part 2

Calculate Crypto Average Price

Promises & Callbacks Quiz

Callbacks & Promises Cheatsheet

Data Fetching

Star Wars Project

Star Wars API Finishing Touches

Star Wars Planets

Data Fetching Quiz

Data Fetching Cheatsheet

Events Cheatsheet

What is the event interface and why is it important?

The event interface in JavaScript represents any event that takes place in the DOM. Events can be user-generated or generated by an API, and they can include anything from basic user interactions to something happening in the rendering model. To interact with the DOM and make your JavaScript react to events, you can add an event listener.

How to add an event listener

The most common way to respond to events is by adding an event listener. When you add an event listener, you tell it what event to listen for and give it a function to invoke when it detects that event has fired. The basic syntax for adding an event listener looks like this:

1document.addEventListener('click', function() {
2  // Logic inside function
3});

In this example, we're adding a click event listener to the entire document, and we're passing in an anonymous function as the second argument. Inside this function, we can put any code we want to execute when the click event is detected.

How to handle events with a function

When you add an event listener, you give it a function to invoke when the event fires. This function is called the event handler, and it can be defined inline or as a separate function. Here's an example of an event handler defined inline:

1document.addEventListener('click', function() {
2  alert('Something was clicked!');
3});
In this example, the function passed as the second argument to
addEventListener
is an anonymous function that simply displays an alert.

The event object and its properties

When an event is detected, the event handler function is automatically passed an event object as its first argument. This object contains properties and methods that are common to all events, such as the type of event that was detected and the element that fired the event. Here's an example of how to access the type property of the event object:

1document.addEventListener('click', function(event) {
2  console.log(event.type);
3});

In this example, we're logging the type property of the event object to the console when a click event is detected.

The difference between adding an event listener and using the "on" attribute

You can also handle events by using the "on" attribute, which allows you to define a function that will be executed when an event fires. Here's an example:

1<button onclick="handleClick()">Click me</button>
2
3<script>
4function handleClick() {
5  alert('Button was clicked!');
6}
7</script>

In this example, we're using the "onclick" attribute to define the function that will be executed when the button is clicked. However, this method has a couple of drawbacks. First, you can only define one function per event. Second, it's harder to remove an event listener that was defined using the "on" attribute.

Multiple events and event types

You can add multiple event listeners to the same element, and you can also listen for multiple event types. Here's an example:

1const button = document.querySelector('#myButton');
2
3button.addEventListener('click', function() {
4  console.log('Button was clicked!');
5});
6
7button.addEventListener('focus', function() {
8  console.log('Button received focus!');
9});
10
11button.addEventListener('blur', function() {
12  console.log('Button lost focus!');
13});

In this example, we're adding three event listeners to the same button element. The first listener listens for the click event, while the second and third listeners listen for the focus and blur events, respectively. Each event listener has its own function that will be invoked when the corresponding event is detected.

Listening for Key Down and Key Up Events

You can listen for key down and key up events using the
keydown
and
keyup
events in JavaScript. Here's an example:
1document.addEventListener('keydown', (e) => {
2  console.log(e.keyCode);
3});
4
5document.addEventListener('keyup', (e) => {
6  console.log(e.keyCode);
7});
The
keyCode
property of the event object
e
contains the Unicode value of the key that was pressed.

Checking the Unicode Value of a Key

To check the Unicode value of a key, you can use the
keyCode
property of the event object
e
. Here's an example:
1document.addEventListener('keydown', (e) => {
2  console.log(e.keyCode);
3});

You can look up the Unicode value of a key online, as there is no logical order to the key codes.

Using the Event API to Prevent the Default Behavior of an Event

You can prevent the default behavior of an event using the
preventDefault()
method of the event object
e
. Here's an example:
1document.addEventListener('keydown', (e) => {
2  if (e.keyCode === 32) {
3    e.preventDefault();
4  }
5});

This will prevent the default behavior of the spacebar key, which is to scroll the page.

Debouncing Events with setTimeout() and clearTimeout()

To debounce events, you can use the
setTimeout()
and
clearTimeout()
methods in JavaScript. Here's an example:
1let timer;
2
3document.addEventListener('keyup', (e) => {
4  clearTimeout(timer);
5  timer = setTimeout(() => {
6    console.log('debounced event');
7  }, 1000);
8});
This will debounce the
keyup
event, so that the callback function is only called after one second of inactivity.

Listening for the DOMContentLoaded Event and the Load Event

You can listen for the
DOMContentLoaded
event and the
load
event using the
addEventListener()
method in JavaScript. Here's an example:
1document.addEventListener('DOMContentLoaded', (e) => {
2  console.log('DOM content loaded');
3});
4
5window.addEventListener('load', (e) => {
6  console.log('page loaded');
7});
The
DOMContentLoaded
event fires when the initial HTML document has been completely loaded and parsed, without waiting for external resources to finish loading. The
load
event fires when all external resources have finished loading, including images and stylesheets.