Learn JavaScript Event Listeners In 18 Minutes

Web Dev Simplified
12 Dec 202018:03

Summary

TLDRThis video from Web Dev Simplified with Kyle offers an in-depth exploration of JavaScript event listeners, suitable for both beginners and experienced developers. It begins with the fundamentals of creating event listeners, explaining how they work, and progresses to more advanced topics like event capturing and bubbling. The tutorial also covers delegation, stopping event propagation, and techniques for running events a specific number of times. Kyle simplifies complex concepts and provides practical examples, ensuring viewers gain a comprehensive understanding of event listeners to enhance their web development skills.

Takeaways

  • πŸ˜€ Event listeners are essential for interactive web development, suitable for beginners and experienced developers alike.
  • πŸ“š The video covers the basics of creating event listeners, explaining how they work and their importance in web development.
  • πŸ” Capturing, bubbling, and delegation are key concepts in understanding how events propagate through the DOM.
  • πŸ‘† The 'target' property within the event object is crucial as it identifies the element that triggered the event.
  • πŸ”„ Multiple event listeners can be added to the same element, and they execute in the order they were defined.
  • πŸ’‘ Event bubbling is the process where an event works its way from the deepest nested element to the outermost element.
  • πŸ” Event capturing is the opposite of bubbling, where the event starts at the outermost element and moves towards the target element.
  • πŸ›‘ The 'stopPropagation' method can be used to halt the event from continuing through the capture or bubble phase.
  • πŸ”„ The 'once' option in event listeners allows an event to trigger just once before automatically removing itself.
  • ♻️ The 'removeEventListener' method provides the functionality to manually remove an event listener when needed.
  • 🎯 Event delegation is a powerful technique for handling events on dynamically added elements without the need to attach individual listeners to each one.

Q & A

  • What is the main topic of the video?

    -The main topic of the video is event listeners in JavaScript, covering their basics, how they work, capturing and bubbling, delegation, and additional tips.

  • What are the two parameters required to create an event listener according to the video?

    -The two parameters required to create an event listener are the type of event to listen for and a callback function that runs every time the event occurs.

  • What is the purpose of the 'target' property in an event object?

    -The 'target' property in an event object refers to the element that was clicked on or the element on which the event occurred. It is important for identifying the specific element that triggered the event.

  • How can multiple event listeners be added for the same element?

    -Multiple event listeners can be added by calling the 'addEventListener' method multiple times with different callback functions for the same event type on the same element.

  • What is event bubbling?

    -Event bubbling is the process where an event works its way from the closest element to the furthest away element in the DOM tree, triggering event listeners for all elements along the path from the target to the document.

  • What is event capturing?

    -Event capturing is the opposite of bubbling. It starts at the outermost element (document) and moves towards the target element, triggering event listeners in a top-down approach.

  • How can you stop the propagation of an event?

    -You can stop the propagation of an event by calling the 'stopPropagation' method on the event object (e) within an event listener.

  • What is the purpose of the 'once' option in the 'addEventListener' method?

    -The 'once' option, when set to true, ensures that the event listener will run only one time and then remove itself, preventing it from triggering again on subsequent events.

  • Why is it necessary to use a separate function for 'addEventListener' and 'removeEventListener'?

    -Using a separate function ensures that the same function reference is used for both adding and removing the event listener. Anonymous functions created inline may not be the same, preventing 'removeEventListener' from correctly removing the listener.

  • What is event delegation and how does it solve the problem of dynamically added elements not having event listeners?

    -Event delegation is the technique of adding an event listener to a parent element that will handle events triggered by its children, even those added dynamically after the listener was set. It leverages the bubbling phase of event propagation to manage events for all matching child elements.

  • Can you provide an example of how to implement event delegation?

    -To implement event delegation, you can add an event listener to a common parent element (like 'document') and check if the 'target' of the event matches a specific selector (e.g., 'div'). If it matches, the callback function is executed, thus handling the event for all elements that match the selector, including those added later.

Outlines

00:00

πŸ“š Introduction to Event Listeners

This paragraph introduces the topic of event listeners in JavaScript, suitable for both beginners and experienced developers. Kyle from Web Dev Simplified promises to cover the basics of creating event listeners, their functionality, capturing and bubbling, and delegation. The video aims to provide a comprehensive understanding of these concepts, which are crucial for web development. Kyle also mentions additional tips and tricks associated with event listeners, ensuring the audience stays engaged until the end of the video.

05:02

πŸ”— Understanding Event Bubbling and Capturing

This section delves into the mechanics of event propagation, explaining the concepts of bubbling and capturing. Kyle demonstrates how events travel through the DOM from the target element to the document, and vice versa, during the capturing phase. He illustrates the process with a practical example involving a 'grandparent', 'parent', and 'child' HTML structure, showing how event listeners are triggered in sequence during these phases. The explanation includes the use of the 'stop propagation' method to halt event propagation, which is essential for controlling event flow in complex applications.

10:02

♻️ Event Listener Management Techniques

In this paragraph, Kyle discusses various techniques for managing event listeners effectively. He introduces the 'once' option to run an event listener a single time before removing it and demonstrates how to use the 'removeEventListener' method to manually remove event listeners. The importance of defining separate functions for 'addEventListener' and 'removeEventListener' is highlighted to ensure they reference the same function, allowing for successful removal. This section provides valuable insights for developers who need precise control over event handling in their applications.

15:03

🎯 Implementing Event Delegation

The final paragraph focuses on event delegation, a powerful technique for handling events on dynamically added elements. Kyle explains the common issue of new elements not having pre-existing event listeners and introduces event delegation as a solution. By attaching a single event listener to a parent element and using the 'event.target' property, developers can manage events for all child elements, including those added later. He provides a step-by-step guide on implementing event delegation and even creates a reusable function called 'addGlobalEventListener' to streamline the process. This approach is particularly useful for large-scale applications with dynamic content.

Mindmap

Keywords

πŸ’‘Event Listeners

Event listeners are functions that wait for a specific event to occur, such as a click or mouseover, and then execute code in response. In the video, event listeners are the core concept, with the script explaining how to create and utilize them in web development. The script demonstrates setting up event listeners for click events on various HTML elements, such as a 'grandparent', 'parent', and 'child'.

πŸ’‘Callback Function

A callback function is a piece of code that is to be executed after another function has finished its task. In the context of the video, the callback function is the code that runs every time an event occurs, such as a click. The script mentions that this function typically takes an 'event object' as a parameter, which contains information about the event.

πŸ’‘Event Object

The event object is a data structure that contains information about an event that has occurred, such as the target element that triggered the event. In the script, the event object is denoted by 'e' and is used to access details about the click event, including the target of the click.

πŸ’‘Event Propagation

Event propagation refers to the process by which an event travels through the DOM. The video discusses two phases of event propagation: capturing and bubbling. The script explains how events naturally bubble up from the target element to the DOM root, and how this can be controlled using event listeners.

πŸ’‘Bubbling

Bubbling is a phase of event propagation where an event works its way from the most deeply nested element to the outer elements, or from the target to the document. The script uses the analogy of 'bubbling up the tree' to describe this process, illustrating it with the example of clicking on a 'child' element and the event listeners on 'parent' and 'grandparent' also firing.

πŸ’‘Capturing

Capturing is the opposite of bubbling and refers to the initial phase of event propagation where the event works its way down from the outer elements to the target element. The video script explains how to set up capturing event listeners and demonstrates the order in which events are handled during the capturing phase.

πŸ’‘Stop Propagation

Stop propagation is a method used to halt the further propagation of an event in the DOM. The script describes how to use the 'stopPropagation' method on the event object to prevent an event from reaching other elements in the DOM, which is useful for controlling the flow of event handling.

πŸ’‘Event Delegation

Event delegation is a technique where an event listener is attached to a parent element instead of individual child elements, allowing for handling events on dynamically added elements. The video script explains how event delegation works by setting up a single event listener on the 'document' and using the event's target to determine if the event occurred on a 'div'.

πŸ’‘Add Event Listener

The 'add event listener' method is used to attach an event listener to an element. The script demonstrates how to use this method by specifying the event type (e.g., 'click') and the callback function that should be executed when the event occurs.

πŸ’‘Remove Event Listener

The 'remove event listener' method is the counterpart to 'add event listener' and is used to detach an event listener from an element. The script shows how to use this method to stop an event listener from executing after it has run a certain number of times or under specific conditions.

πŸ’‘Once Option

The 'once' option is a property that can be passed to the 'add event listener' method to specify that the event listener should only run once and then be removed. The script mentions this option as a way to ensure an event listener is executed only a single time, which is useful for one-off actions.

Highlights

Introduction to the video on event listeners, aimed at both beginners and experienced developers.

Explanation of creating an event listener and its basic function.

Discussion on event capturing, bubbling, and delegation, which are crucial for understanding how event listeners work.

Demonstration of setting up a click event listener on a 'grandparent' element in an HTML file.

Explanation of the 'event' object and its properties, particularly the 'target' property.

Illustration of adding multiple event listeners and their execution order.

Clarification on why clicking a 'child' element triggers event listeners on 'parent' and 'grandparent' elements.

Introduction to the concept of event bubbling and how it traverses from the target element to the document.

Explanation of the capturing phase of event propagation and how it differs from bubbling.

How to use the third parameter in 'addEventListener' to initiate the capture phase.

Demonstration of the sequence of event capturing and bubbling with multiple elements.

Introduction to the 'stopPropagation' method to halt event propagation during capturing or bubbling phases.

Use of the 'once' property in the options parameter to run an event listener only once.

Explanation of how to remove an event listener using the 'removeEventListener' function.

The importance of using named functions for 'addEventListener' and 'removeEventListener' to ensure correct removal.

Introduction to event delegation as a solution for handling events on dynamically added elements.

Demonstration of how event delegation works by adding an event listener to the 'document' and using the 'target' property to filter events.

Creation of a utility function 'addGlobalEventListener' for simplified event delegation.

Conclusion summarizing the comprehensive coverage of event listeners in JavaScript.

Transcripts

play00:00

whether you're a complete beginner just

play00:01

learning how to use event listeners

play00:03

or if you've built multiple projects on

play00:05

your own using event listeners all the

play00:07

time

play00:08

i can guarantee you there's something in

play00:09

this video you don't already know

play00:12

[Music]

play00:15

welcome back to web dev simplified my

play00:17

name is kyle and my job is to simplify

play00:19

the web for you

play00:20

so you can start building your dream

play00:21

project sooner so if that sounds

play00:23

interesting

play00:23

make sure you subscribe to the channel

play00:25

for more videos just like this

play00:27

now like i mentioned in the intro we're

play00:28

going to be covering a ton of

play00:30

information related to event listeners

play00:32

we're going to start at the very basics

play00:33

of how you create an event listener and

play00:34

how they actually work

play00:36

then we're going to talk about capturing

play00:37

bubbling and delegation

play00:39

and how all of that works because it's

play00:40

incredibly important to understand

play00:42

and most people really don't understand

play00:44

it well enough and then finally we're

play00:45

going to talk about a few minor tidbits

play00:47

here and there

play00:48

of bonuses that come with event

play00:49

listeners so this video is going to be

play00:51

jam packed full of information so make

play00:53

sure you stick around till the end to

play00:54

get all the information you need

play00:56

now to get started i have a really

play00:57

simple index.html file

play00:59

where we have a grandparent inside that

play01:01

we have a parent and inside that we have

play01:03

a child

play01:03

you can see on this right hand side we

play01:04

have this red grandparent blue

play01:06

parent and then green child and what

play01:09

we're going to do is set up event

play01:10

listeners for when we click

play01:11

on these elements so the very first

play01:13

thing i want to do is set up a click

play01:15

event listener on the grandparent

play01:17

in order to do that all we need to do is

play01:19

take the grandparent element

play01:20

so just type in grandparent and we put a

play01:23

period and as you can see the very first

play01:24

thing on this list is called add event

play01:26

listener so just type in add

play01:27

event listener and this is going to take

play01:29

two to three parameters for now we're

play01:31

just going to start with the two

play01:32

parameter version because that's the

play01:33

most common

play01:34

the first parameter you put in here is

play01:36

going to be the type of event that you

play01:38

want to listen for

play01:39

in our case we're listening for a click

play01:41

event there are

play01:42

tons and tons of events you can listen

play01:44

for and if you want to know what they're

play01:45

called just google

play01:46

you know mouse down event or mouse over

play01:48

event and it'll give you the exact name

play01:50

that you're looking for if you don't

play01:51

already know it

play01:52

the next thing we need to pass here is a

play01:54

callback and this callback is just a

play01:56

function that runs

play01:57

every single time that we do whatever

play01:58

the event is in our case click

play02:00

and this takes a single parameter which

play02:02

is the event object

play02:04

generally you'll see this called e we're

play02:06

just going to use an arrow function for

play02:07

our use case

play02:08

if you don't already know arrow

play02:09

functions make sure to check out my

play02:10

video linked in the cards and

play02:11

description

play02:12

it covers arrow functions in depth so

play02:14

now let's just come in here and do a

play02:16

console log of

play02:17

e to see exactly what this e is so now

play02:20

if we just come over here

play02:21

click on the grandparent you're going to

play02:22

notice we get this massive event down

play02:23

here with tons of information inside of

play02:25

it

play02:26

a lot of this information deals with

play02:27

where your mouse is on the screen

play02:29

it deals with where you're holding down

play02:30

like the control key for example there's

play02:32

a bunch of information inside of here

play02:33

but probably the most important

play02:35

information that you're going to care

play02:36

about is this thing called target right

play02:37

here

play02:38

target is essentially the thing that you

play02:40

clicked on in our case the grandparent

play02:42

so that is the target and target is just

play02:44

an element so it has all the normal

play02:45

element related information

play02:47

inside of it but generally when you're

play02:49

dealing with click event listeners or

play02:50

any event listener target is usually the

play02:52

most

play02:52

important thing that you want to mess

play02:53

with inside of the event listener

play02:55

because it is the thing

play02:56

that the event happened on so in our

play02:58

case that would be this grandparent

play03:00

so if we just console.log e dot target

play03:03

and i click on this again you're gonna

play03:05

see it prints out that grandparent

play03:06

element

play03:07

now one thing that's also interesting

play03:08

about event listeners is we'll just

play03:10

change this to print out

play03:12

grandparent one what we can do is add

play03:14

multiple event listeners so if i just

play03:16

copy this

play03:17

asa down here and put grandparent two

play03:19

inside of it and i click save

play03:21

when we click on this you're going to

play03:22

notice it's going to run both of the

play03:23

event listeners in the order that we

play03:25

defined them so grandparent one goes

play03:26

first because that's the first one we

play03:27

define

play03:28

and then grandparent two comes second

play03:30

because that's the second one that we

play03:31

define

play03:32

as the default behavior of event

play03:34

listeners and this right here is what

play03:36

most people understand when it comes to

play03:37

event listeners they know how to put the

play03:39

type in

play03:39

they know how to create a callback

play03:41

function and they know that they run in

play03:42

the order that you define them

play03:43

that's about where most people's

play03:45

knowledge stops so in the rest of this

play03:46

video we're gonna go beyond

play03:48

just this basic information and talk

play03:50

about everything else that there is to

play03:51

know about event listeners

play03:53

like for example you'll notice when i

play03:54

click on this child it still prints out

play03:56

the grandparent information

play03:58

why exactly is that well to figure out

play04:00

let's first set up event listeners for

play04:02

our parent and our child

play04:03

so let's just come in here we're going

play04:04

to copy this grandparent one

play04:06

paste it down and in here we're just

play04:08

going to say

play04:10

oops parent and this will just say

play04:13

parent and then we're going to do the

play04:14

exact same thing

play04:15

for child so here we'll say child

play04:19

and child so now if we click grandparent

play04:22

it'll print grandparent

play04:23

when we click on the parent you're going

play04:24

to notice it prints out parent one

play04:26

and then grandparent one and now when we

play04:28

click the child it's going to print

play04:29

child one

play04:30

parent one and then grandparent one so

play04:33

if you're paying attention essentially

play04:34

what's happening

play04:35

is that it's we're clicking on this

play04:36

element but behind this green child

play04:39

is also our blue parent and behind our

play04:41

blue parent is our red

play04:43

you know grandparent here and even

play04:44

further behind that is our actual

play04:46

document itself

play04:47

which we could set up an event listener

play04:48

for for example document

play04:50

dot add event listener click and we're

play04:53

just going to come in here

play04:55

and we're going to console.log

play04:59

document1 so now if we click the

play05:01

document it prints out document we click

play05:02

here it prints out child

play05:04

parent grandparent and then document and

play05:06

that's because it's working its way from

play05:07

the closest element in our case this

play05:09

child

play05:09

all the way to the furthest away element

play05:11

which is our document

play05:12

and it's running click event listeners

play05:14

for all of them because we technically

play05:15

clicked on all of them since the child

play05:17

is inside the parent

play05:18

and the parent is inside of the

play05:19

grandparent and the grandparent is

play05:20

inside of the whole document itself

play05:22

this process of going from the closest

play05:24

element to the furthest away element

play05:26

is something called bubbling you also

play05:28

might hear it called event bubbling

play05:30

and this is one half of how events work

play05:32

inside of javascript

play05:34

the other half of how they work is

play05:35

called capturing

play05:37

so if i just go to this elements tab

play05:38

here i'm going to expand this up so we

play05:40

can really see what we're working with

play05:42

get it as large as i can and open up the

play05:44

grandparent parent and the child

play05:45

so you're going to see at our very first

play05:47

when we click on our page

play05:49

we click inside the child right so our

play05:51

click is going to start at the child

play05:52

here it's going to go down to the parent

play05:54

go down to the grandparent and then all

play05:55

the way down to the document as its

play05:56

final step it's kind of working out of

play05:58

its hierarchy

play05:58

because we clicked on all of them well

play06:00

that is like i said the bubbling phase

play06:03

there's a second phase called the

play06:04

capturing phase and this actually

play06:06

happens first

play06:07

the way the capture works is it works

play06:09

for the thing furthest away and moves up

play06:11

so it'll start with the document then

play06:12

the grandparent then the parent then the

play06:14

child

play06:15

then we swap over to the bubble phase

play06:17

where we go from child

play06:18

to parent to grandparent back to

play06:20

document the way to remember this that i

play06:21

like to think about it

play06:22

is when you bubble generally bubbles

play06:24

move upward because they're light

play06:26

so you bubble up the tree so you start

play06:28

down here at the lowest

play06:29

most minute element and you bubble

play06:31

upwards out of the tree that's how i

play06:33

like to remember capturing versus

play06:34

bubbling

play06:35

like i said capture starts on the

play06:36

outside moves in and then bubbling

play06:38

happens second

play06:39

and goes from the inside out but right

play06:41

now all of our events are bubble events

play06:43

because as you notice we print child

play06:45

then parent then grandparent

play06:46

and document in that order because

play06:48

they're all bubbling so how exactly

play06:50

do we do a capture that is where this

play06:52

third parameter

play06:53

to the add event listener comes into

play06:55

play we can pass in here an option

play06:58

these options is just an object where we

play07:00

pass in different parameters to it so we

play07:01

could

play07:02

pass capture and set it to true by

play07:05

default this is set to false

play07:06

but if we set it to true we're saying we

play07:08

want this event to be a capture event

play07:11

so now if i save this and i click on the

play07:13

child you're going to notice something

play07:15

interesting it prints grandparent one

play07:17

then child one then parent one then

play07:18

document one and that's because our

play07:20

grandparent is in the capture phase

play07:23

so if we just go to our html here real

play07:24

quick what's happening is we start with

play07:26

the capture which means we start at our

play07:28

document

play07:28

then we move to our grandparent which we

play07:30

set up a capture event on so it prints

play07:32

out here

play07:33

then we do the capture for our parent

play07:35

there is no capture event so we skip it

play07:37

do the capture for our child again there

play07:39

is no capture for our child so we skip

play07:40

it

play07:41

and then we do the bubble so we bubble

play07:42

our child where it prints out child one

play07:44

do the bubble for our parent where it

play07:45

prints out parent one bubble for our

play07:47

grandparent

play07:48

and since we swapped this to a capture

play07:50

event there is no bubble phase so it

play07:52

skips it

play07:52

and then we do the bubble for our

play07:53

document which finally finishes this all

play07:55

off

play07:56

so this is how the capturing and

play07:57

bubbling system works and to really see

play07:59

in depth how it works

play08:00

what i want to do is just copy all of

play08:02

these events so we can have grand

play08:04

apparent

play08:06

capture and then we're going to have

play08:07

grandparent

play08:09

bubble which is just the default so i'm

play08:12

going to remove that

play08:13

and i'm just going to copy this down a

play08:15

couple times so we have

play08:16

all of them so we got the parent this is

play08:19

going to be

play08:20

parent capture parent here

play08:26

parent bubble then we're going to have

play08:28

our child

play08:31

and our child capture

play08:35

then we're going to do the bubble for

play08:36

our child right here so

play08:38

child bubble and then we can even finish

play08:41

this off by doing the document as well

play08:42

so we got document

play08:44

bubble and we each copy this

play08:48

you can get the document capture as our

play08:50

final one

play08:51

the document here document capture

play08:54

so now if i click on this child it's

play08:56

going to go document capture grandparent

play08:58

capture parent capture child capture

play09:00

and then it goes back down the tree with

play09:02

the bubbling so child bubble parent

play09:03

bubble grandparent bubble document

play09:05

bubble

play09:06

starts on the outside captures inward

play09:08

then goes from the inside and bubbles

play09:10

outward

play09:10

that's how these events work now this is

play09:12

all great that we have the capture and

play09:14

bubble phase

play09:15

but sometimes there are things that are

play09:16

going to happen that prevent the event

play09:18

from going through the entire capture

play09:20

and bubble phases

play09:21

and this is what happens when you stop

play09:23

the propagation of an event

play09:25

so let's say that when we get to the

play09:27

parent capture

play09:28

we want to stop all propagation we want

play09:30

to say you know what

play09:31

once the parent gets the event we want

play09:33

to stop and have nothing else get it

play09:35

so if we find our parent capture here we

play09:37

can take our event object which we

play09:39

called e

play09:39

and call the stop propagation method on

play09:42

it

play09:42

now when we click on the child you're

play09:44

going to notice it goes document capture

play09:46

grandparent capture and parent capture

play09:48

and then none of the other capture

play09:50

phases or bubble phases occur

play09:52

because what we did here is we stopped

play09:54

the propagation of our event which means

play09:56

it just immediately stops it doesn't do

play09:58

any more capturing or

play09:59

any more bubbling which is why we only

play10:01

get these three being printed out

play10:04

if we move this now instead into let's

play10:06

say our child bubble

play10:08

we just paste it in here you're going to

play10:09

notice it goes through the whole capture

play10:11

phase

play10:12

for all of our elements and then as soon

play10:13

as the child bubble happens it stops

play10:15

propagation and none of the other

play10:17

bubbling for the parent

play10:18

grandparent or document occur so we can

play10:20

use e dot stop propagation

play10:23

to stop our event from propagating

play10:24

upwards or downwards through the capture

play10:26

or bubble phase

play10:28

now i just want to clean this up a

play10:29

little bit we're going to get rid of our

play10:30

document events and we're going to get

play10:31

rid of all these capture events as well

play10:33

so we're just left with

play10:34

our original three events that we set up

play10:36

here so we have grandparent

play10:37

parent and child and when we click if we

play10:40

get rid of this stop propagation

play10:42

you can see we get child bubble parent

play10:44

bubble and grandparent bubble now

play10:46

another thing i want to talk about is a

play10:47

really common thing that you need to do

play10:48

with events and that's when you want to

play10:50

run an event once

play10:51

and never run it again you can use this

play10:54

third options parameter here inside of

play10:56

your ad event listener and you can pass

play10:58

it a property of once

play11:00

set that to true and this event will run

play11:02

one time and then remove itself

play11:04

immediately

play11:04

so if we click you can see we got child

play11:06

parent grandparent click again

play11:08

we just get child and grandparent

play11:10

because parent was set up to run

play11:11

only one time which is really useful if

play11:14

you need an event just to happen one

play11:15

time

play11:16

and we can click as many times as we

play11:17

want the parent is never going to show

play11:19

up here

play11:19

what happens if you maybe want an event

play11:21

to run three times or four times or five

play11:23

times or you want to

play11:24

stop it on your own and not just after

play11:25

one event well what you can do instead

play11:28

is use the dot remove event listener

play11:32

function this works just like the add

play11:34

event listener you pass it the type and

play11:36

function

play11:36

and will remove that function from your

play11:38

event listener

play11:39

so if we just come down here and create

play11:41

a function called print

play11:43

i and we just say console.log

play11:48

i make it capitalize there we go and

play11:51

when we do the parent here

play11:52

what we want to do instead is print

play11:55

i then we can remove that event listener

play11:58

at a later point

play11:59

so let's just say set timeout

play12:02

and this is just going to run some code

play12:04

after let's say

play12:05

two seconds so 2000 milliseconds we're

play12:08

going to do

play12:09

dot remove event listener on the click

play12:12

event

play12:12

and we want to remove that print high

play12:14

function

play12:15

so now if i run this and i click you can

play12:17

see it prints out high for our parent

play12:19

but if we wait you know two seconds and

play12:20

then click again you can see it has

play12:22

removed that event listener for us

play12:24

by using the parent.remove event

play12:26

listener and the reason i created a

play12:28

function separately for this

play12:29

is that if we wrote this code inline

play12:31

like this console.log

play12:33

i and we just copy this over

play12:36

to here remove this function down here

play12:40

you'll notice this doesn't actually work

play12:41

we can click a bunch of times it prints

play12:43

out high

play12:43

and now if we wait two seconds it's been

play12:45

about two seconds we click again

play12:46

it's still printing out high as you can

play12:49

see here and the reason for that

play12:50

is that this function and this function

play12:53

over here while they look

play12:55

identical are actually two different

play12:56

functions because you created two

play12:58

anonymous functions

play12:59

so they aren't the same which means

play13:01

remove event listener can't remove it

play13:03

because this event is technically a new

play13:05

event and it's different from the

play13:07

original event we added it to

play13:09

that's why if you want to use remove

play13:10

event listener you need to create a

play13:12

variable or function or something

play13:13

that is the same for both of the add and

play13:16

remove event listener

play13:17

now the very last thing that i want to

play13:19

talk about is going to be how you

play13:20

delegate

play13:21

events because this is really important

play13:22

when it comes to dynamically adding

play13:24

elements to your page

play13:25

let's just get rid of all that we're

play13:27

just going to select all of the divs on

play13:29

our page so document.queryselector

play13:31

all or our divs and each one of these

play13:34

elements is a div so it's just going to

play13:35

select all of our elements

play13:37

and then we just want to loop through

play13:38

our divs so we'll say for each div

play13:41

all we want to do is add an event

play13:42

listener

play13:45

oops not console log div dot add event

play13:47

listener

play13:48

on click and we just want to print out

play13:51

for example

play13:52

console.log i there we go

play13:56

now when we click on a div it's going to

play13:58

print out height if we click on one of

play13:59

the middle divs it's going to print high

play14:00

for each one of them

play14:01

that works just fine but now let's say

play14:03

that we want to create a new div so

play14:04

we're going to say new

play14:05

div is equal to document.createelement

play14:10

of div and then we're just going to

play14:11

append that to the end of our body so

play14:13

body

play14:14

dot append new div let's make sure we

play14:17

just give this div some styles so we can

play14:18

see it

play14:19

so new div dot style dot

play14:22

width equals 200 pixels

play14:27

new div dot style dot height equals 200

play14:31

pixels and we'll just say

play14:34

new div dot background i'm sorry dot

play14:38

style

play14:40

dot background

play14:43

color we're just going to set this to

play14:45

purple

play14:47

so now you can see we have this new div

play14:48

over here and we click these divs they

play14:50

all print out high just like we expect

play14:52

when i click this div it doesn't print

play14:54

high the reason for that

play14:56

is that up here i selected all of the

play14:57

divs on my page i added event listeners

play14:59

to them

play15:00

and then after i did that i added a new

play15:02

div

play15:03

and then i you know put it on the page

play15:05

but this one wasn't selected up here

play15:06

because the selector was ran

play15:08

before i created this new div this is a

play15:10

problem a lot of people that are new to

play15:12

javascript and event listeners run into

play15:13

is they think that the new div will have

play15:15

the event listener but it actually

play15:17

doesn't because it was added after the

play15:18

event listeners were added

play15:20

we could come in here and say new div

play15:22

dot

play15:23

add event listener per click

play15:26

and you know we could come in and make

play15:28

sure that we console log high inside of

play15:30

here

play15:30

and now it'll work because we added the

play15:32

event listener after the fact

play15:34

this is kind of clunky and it's really a

play15:35

pain to do this

play15:37

so instead what i like to do is event

play15:39

delegation

play15:40

since you know that our events go

play15:41

through the bubble and capture phase

play15:43

we know that all of our events

play15:44

eventually end up on the document

play15:46

we could say document.addeventlistener

play15:49

for click

play15:50

and inside of here we can just

play15:52

console.log hi

play15:55

now what this is going to do is just log

play15:56

high every time we click on our page

play15:57

whether we click on one of our divs or

play15:59

if we click on our body or anywhere else

play16:01

so clearly it's not quite what we want

play16:03

because it works everywhere and we only

play16:04

want it to work when we click on a div

play16:07

so what we can do is take that event

play16:09

property called e

play16:10

we can get the target from it we can

play16:12

call a function called matches

play16:14

this just takes a css selector and if

play16:16

the

play16:17

target matches it it returns true so we

play16:19

could pass div as our selector here and

play16:22

then if

play16:22

this is true that means we've clicked on

play16:24

a div so let's log out hi

play16:26

and now when i click instead of a div

play16:29

you can see we get our high being logged

play16:30

out

play16:31

but when i click over outside of a div

play16:33

you notice no high is being printed

play16:35

but our new div will print out hi just

play16:37

like we wanted to

play16:38

so this is perfect and does exactly what

play16:40

we want i use this kind of code

play16:43

all the time which is why generally i

play16:44

like to turn this into a function

play16:46

i like to just call it add global event

play16:49

listener

play16:50

which takes in a type a selector and

play16:53

then a callback

play16:54

and inside of here i just like to add my

play16:56

event listener

play16:58

whoops add the event listener or the

play17:00

type i like to

play17:02

then have my callback here and inside of

play17:04

this

play17:05

what i do is i just say if

play17:07

e.target.matches

play17:09

oops matches selector

play17:14

then i call the callback with the event

play17:16

this right here

play17:17

does the exact same thing as what we

play17:18

have up here so i could just say add

play17:20

global event listener for click

play17:22

and i want it to match a div

play17:26

then i can just get rid of all this code

play17:28

and now if i run this

play17:29

we get the exact same thing when we

play17:30

click a div it prints out hi and

play17:32

anywhere else it doesn't

play17:33

and essentially all that i did is i just

play17:35

wrapped that code inside of a nice handy

play17:37

function which i can call anywhere which

play17:38

takes a selector

play17:39

i'm sorry a type a selector and then a

play17:42

callback for whenever we click on

play17:43

something that matches this selector

play17:45

super handy function i like to include

play17:46

it everywhere and that's all there is to

play17:49

event listeners in javascript

play17:51

if you enjoyed this video make sure to

play17:52

check out my complete javascript

play17:54

simplified course linked down below

play17:56

it covers literally everything you need

play17:58

to know about javascript

play17:59

and with that said thank you very much

play18:01

for watching and have a good day

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
JavaScriptEvent ListenersWeb DevelopmentBubblingCapturingDelegationDOM ManipulationWeb TutorialBeginner GuideAdvanced TipsEvent Propagation