Event Listeners in JavaScript | JavaScript Events Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Splendid work!

๐Ÿ‘๏ธŽ︎ 2 ๐Ÿ‘ค๏ธŽ︎ u/ADRIANT9 ๐Ÿ“…๏ธŽ︎ Dec 21 2020 ๐Ÿ—ซ︎ replies

In this video we'll learn about Event Listeners in JavaScript with addEventListener. We'll also explore Event Bubbling, Event Capturing, Event Propagation, and Prevent Default Behaviors. We'll look at the click event, readystatechange event, mouseover & mouseout events, and the submit event while using both named and anonymous functions as event handlers. We'll also work with the add, remove, and toggle methods of a classList. Let's get started!

โœ… Quick Concepts outline:

JavaScript Event Listeners

(0:20) Insure the DOM is available to interact with

(1:30) How to load your script for DOM interaction

(3:30) Syntax: addEventListener(event, function, useCapture)

(4:50) Using a function name in the event listener

(5:55) Removing a function with a name: removeEventListener()

(6:50) Using an anonymous function in the event listener

(8:50) Listening for the readystatechange event

(10:30) Constructing an initApp() function

(13:30) Event Bubbling

(16:00) Event Capturing

(17:00) Event Propagation and stopPropagation()

(21:45) event.target usage

(25:05) classList, add, remove, and toggle

(34:50) Listening for a HTML Form submit event

(36:20) HTML Form default behavior

(37:00) Prevent default behavior with event.preventDefault()

If you enjoy this video, check out the ones that follow it in the playlist. Iโ€™ll continue to add more. Glad to answer your questions, too.

Event Listeners in JavaScript | JavaScript Events Tutorial: https://youtu.be/UVRDq-wnfgk

๐Ÿ‘๏ธŽ︎ 1 ๐Ÿ‘ค๏ธŽ︎ u/DaveOnEleven ๐Ÿ“…๏ธŽ︎ Dec 20 2020 ๐Ÿ—ซ︎ replies
Captions
hello and welcome today we are learning about javascript event listeners and we will also review event bubbling capturing propagation and default behaviors let's get started today we're looking at javascript event listeners but before we can interact with the document object model we need to ensure that the dom has actually loaded into the browser and is ready to interact with so let's look at an example of that first i'm going to define a view variable i'm going to set that equal to the view i have defined use a query selector and i'll look for the id view too that's the one we're looking at here and then i'm going to log to the console the view i'll save this and you can see in the console we get null now why is that if i inspect the elements that i have on the page you can see i have a view one section here's my view to section that we're looking at right now and so it's there so why in the console would that be null well we have to look at our html and where we put our javascript in the html document my script tag is in the head tag of the document and you can see it doesn't have any extra information other than the script and the source attribute and this is why we're getting null in the console because the script is loading here and then the tags the document that i'm trying to interact with load after that so when my query selector tries to select the element it really doesn't exist yet so many times because of this you'll see pages that have the script tag at the bottom right before the closing body tag and if we save that now we don't get null in the console so that does work but there is another method that is a little bit newer that you'll see with an attribute and that is the defer word the keyword defer that you can put in the script tag and then leave the script tag in the head of your html document and you can see that also works in the console so that's the very first thing i wanted to draw attention to we have to make sure those dom elements and anything else nodes that we're trying to interact with in the dom have actually loaded before we try to work with those okay so we've defined a view and we logged that to the console let's move on from there and let's define something from the view we could go ahead i'll get rid of this console log and we can define a div that we have inside the view so we can start our query selector with view now say query selector and just select the div element that's inside of that view and then inside of the div i have an h2 so then we can start with div and use a query selector and select that h2 element so now that we have all three of those defined let's look at the syntax for a event listener or adding an event listener so here's the syntax we'll have add event listener and then for the parameters that we put we put the event we want so this would be a click event and then i'll put a comma and then we would put a function whatever kind of function we want to call and then there is a use capture option as well that we'll talk about so i should just put here instead of click since i'm just talking generically this would be the event whichever kind of event a function and use capture and there are many types of events not just clicks in this first example though we will use a click so let's define a function that we can go ahead and call when we have a click event so let's call this function do something just a very generic function and it will launch an alert and the alert will say doing something now to add this as an event listener or actually as a response to an event listener let's go ahead and add an event listener to our h2 element and we have already defined that up here as a variable so we can just start with h2 and then we'll put add event listener and i'm going to put the click event in that first position and then i'm going to put the name of the function that i want to add and then i'll put false in the use capture position and it's worth noting that this false is the default so if we were to omit that it would have the same result it would be considered false and we'll come back to that use capture but when we do this this will add a click event listener to our h2 element so i'll save that and now in our page when i click the h2 element we get the alert doing something and so you are interacting with the page at that point that's a very simple way a very simple demonstration but a very simple way to interact with the page and a click event is something that is very typical because we click all over web pages now if we didn't want this on here or maybe we just wanted to remove it later on we can also remove an event listener when we have a name of the event and i mean not the event i'm sorry the function we can remove the event listener and it's a click event again and then we're removing the do something function and again it was false so now when i load this it added it but then it immediately removed it so it does no longer it launches the alert and it's just kind of a null prospect in that regard because we added it and then we removed it immediately and it's not going to work for us at that point but if this was an anonymous function we would not be able to remove that so let's look at how we can add an anonymous function with an event listener as well so i'll put the h2 and i'll say add event listener it's a click again and at this point i'm going to put event and sometimes you'll see that represented as an e or maybe an evt you could really name it anything you want but it's the event so i'm going to stick with that name but just keep in mind you may see it referred to differently when you're looking at other code okay so what we've got here is a function i'm using an arrow function but it's an anonymous function we didn't name the function and now we can just put in what the function does so i'm going to put a console log and i'm going to log the event dot target and let's take a look at what that event target is i've saved that i'll click and the event target is the actual element so the target is what we clicked we clicked that and i logged the event target and now maybe let's change the text content of that event target so the event target dot text content and we'll just put clicked i'll save that and now when i click we change the text to clicked and we did log the event target once again so that is how you can add an anonymous function also this would work if you did not use an arrow function but use the traditional function keyword save that again click and it has the same uh exact same action afterwards okay now that we've been introduced to event listeners and the click event let's look at a few more examples and the first thing i want to do is look at an event that also makes it safer to start working with the document object model the dom when you load the page and that is the ready state change event so i'm going to immediately say document add event listener and i'm listening for the ready state change event and it is an event i'll put here again i'm going to use an arrow function and then i'll put an if statement if the event.target.ready state and the event target is the document itself at this point equals complete then we can log to the console and i'm going to put ready state complete the page is ready in other words it's kind of like saying the page is loaded although it is not exactly the same as saying the page is loaded we could take a deeper dive beyond the introductory javascript videos as to the different stages of a page load but if you look for the ready state being complete you will know that your page is loaded enough that the dom is loaded and you're ready to interact with so let's go ahead and save this and you can see we get ready state complete right away it's just part of the page loading process at this point you could now call another function like init app and this is fairly common to have a function to kick off your web app your program that is called init or init app something like that so we'll call ours a knit app and at this point your init app could start loading other event listeners and start interacting with the dom because you would know your page is ready the ready state is complete and you are ready to go let's define our init app function we'll make this an arrow function and the first thing i'm going to do are take these variables we have at the top the view div and h2 and i'm going to put them inside of our init app function we know the page is ready to go and we will not get in all values for those and then on the view i'm going to add an event listener that's going to be a click event listener and inside this event listener we're going to refer to the variable we have defined above within the scope of this init app and we'll say view dot style dot background color and let's set that to purple now i'm going to copy this and just change a few things as we do the same for our div and our h2 and we don't want them all to be purple so let's change that we'll go with blue and let's not change the background color of the how do i get elements by class name there i didn't notice that i'm meant to have view that style that background color there oh one more there we have that style dot background color but the last one though the h2 event listener we don't want that we're going to put something in completely different let's say event dot target dot text content like we did previously and there we'll say clicked okay now that we have this set up you will probably be surprised at the result so what we're going to look at is something called event bubbling now notice in each of these event listeners we did not put in the third use capture parameter it is optional so it immediately uh chooses faults by default so it would be kind of like we have a comma after that and we say false here that's what the default is already and that means we're not going to use capture and that means we prefer event bubbling so let's see what happens when i click and then we'll talk about the different chain of events actually so i'll click the h2 and everything changed now why did everything change i just clicked the h2 let's talk about this the first thing we have is the text content changing but then even though i just clicked the h2 it is inside the div and so the event bubbles up and it triggers the click event for the div as well and so the div changed to a background color of blue and the div is inside the view that's a section element with the id view and so that event bubbled up once again and it triggered the click event listener for the view and it changed it to purple so that is worth noting that events can bubble up and that is the default because the use capture was false and notice it goes up or outward because we had the h2 inside the div the div inside the view section that i had defined and it went from one to the next to the next however if we change that and we put that to true we can change each one of these to true just so they behave in the same way now we're saying use capture is true and notice prettier reformatted my code for me when i saved the file but it's it's at the same thing it's just formatted a little differently here so the true is here on its new line um now we are going to use the capture now i'll click again and everything changed once again but what happens is it starts from the outermost element and works its way inward and we can visualize this even better if we use something called stop propagation so i'll start with the outermost element and i should be able to put let's see the click event and true so here where the purple is i should be able to put well let's put it before changing stop propagation now i click and we only get the purple change notice the div didn't change color the text didn't change and that is because we are using the capture option so that's set to true use capture even though i clicked the h2 which would have triggered all those if we were using bubbling event bubbling is what that's called when you work from the in side to the outside but we're using capture instead so that works from the out to the in and so the outermost element that had a click event being the view that we defined here it's actually id of view two but it's our view variable that we define now we have the click event listener on it and it changes to purple but since we stopped the propagation it didn't propagate to the div and from the div down to the h2 now let's go ahead and get rid of these trues put them back to the default faults and i'm going to remove the stop propagation here i'm going to put the stop propagation on the h2 and i'll save that when i click it changes the text but it doesn't propagate itself outwards so the div doesn't change and now the the section the view section that i defined does not change and so i hope that makes sense in how the propagation works now we could take it and move this to the div and so now i'll save this one more time when i click the h2 it will propagate to the div but then the event propagation will stop and it will not move out to the section that i have identified as a view here we go click and yes that changed and the div changed to blue but the section did not change so we have stopped the event propagation so it all depends on what we set if we leave out the third option in the syntax of the listener the use capture if we leave it out or set it to false it's the same thing because it defaults to false but if we set it to true it works from the out to the innermost element or the innermost click event because that's what we're doing is it's working its way out it's propagating or working its way in when we've set capture to true working its way out when we've set it to false but either way it is propagating that event and if there is another listener for the same event and in this instance we have a click listener on each one of these elements that click event is propagating either out or inward and each one of these listeners is being called so many times we actually want to stop the propagation because we don't want something else in our web app to respond to a click event that we really only wanted to impact one thing now i'm going to remove the event stop propagation and we'll go ahead and let those propagate so i'll save that we'll make sure it's working as expected and yes it is but what we need to talk about is the event target so h2 this ad event listener actually worked with the event target it's what i clicked on and that's fine but this worked with the div itself not the event target so let's put event dot target in this spot and this worked with the view not the event target so let's put event target in this spot and once again you may be surprised at what we get as results so when i click on the h2 notice the background of just the h2 turned to purple the div did not change so we didn't get the same result now let's talk about why that works this way that is because the event target that i clicked on was the h2 and previously the background of the h2 didn't turn purple but in this instance it did so what happened well the text content once again changed to click and then the event the click event propagated and it went up here to the div event listener and it is reacting to or it is changing modifying the event target the event target is no longer the div it is the h2 so it changed the background color of the h2 to blue but then when that propagated up here to our view it also changed the background color so the background color became purple and that's what we have now i just clicked on the div and now that's the event target so when i clicked on the div it changed the background color to blue but then up here once again referring to the div as the event target now it changed the background color of the div to purple and then of course if i click on the section that has that is known as the view it also turns purple so that is also something to consider when you use the event target what are you really referring to it's not necessarily referring to what we have added the event listener to it's actually the event target and that is why previously i had this as a div and i had this as the view so it would respond like i wanted it to and then when i clicked each thing or each piece of the puzzle kind of worked its way outward and responded like we wanted it to now that didn't turn purple for a second that's because i still have the word target there there we go save that now i'll click and there we go clicked blue purple as expected but the event target will always refer to what was actually clicked on or if it's not a click it will refer to whatever event was targeted or whatever element was targeted for the event before we move on to more ad event listener examples let's go ahead and take a look at what we're doing inside of these two event listeners the one that is listening for a click on the view we've defined and the one that is listening for a click on the div we've defined so the blue section and the black box here as well as the div what we want to do is consider the style property we're accessing to change the css background color while i think it is important to know how to access each part of the style property because there could always be a time you might need to do that never say never what we do want to do is learn how to add classes because typically you would apply your css styles or in this case sas is what i'm using it is still basically turns into css we want to learn how to apply those styles by applying classes and through javascript you can do that as well and this is a good time to look at that since we're changing colors so what we have is a purple background when this happens so let's go ahead instead of having style background color let's access the class list for the view and we will say we want to add a class in this instance i have a class name purple i'm going to add that let's go ahead and look at our html because if there is another class or color already defined then this adding this class will not overwrite what is already there so let's take a look and our view 2 has a class view it also has a class that is dark blue so we need to consider removing that class at the same time if we actually want that to change to purple so if we put view class list remove and then we need to remove the dark blue class as well as add the purple class i'll save that now let's click and see what happens not read the add property of undefined and that is because i left an s out of the class there we go one more time and it changes purple like we expected it to however there's no going back once we're purple we're stuck we have the add and the remove we've removed the dark blue class we've added the purple class javascript makes it easier than than just this because we can actually change the add and remove to the word toggle and toggle will understand that if the purple class is not added that it should add it and if the purple class is added it should remove it and so it will do the same for dark blue so we start out with dark blue being added and purple not so when i click and i'll just click the view instead of even worrying about the propagation now it changes to purple but if i click again it's back to dark blue and so that's a pretty cool way of changing something and changing it back remember you can add and remove classes but it's also possible to toggle classes and that lets you add and remove in a smart way that lets you of course interact with the page instead of making a change and then not being able to change it back now just because of that possibility let's go ahead and do the same thing for our event listener on the div and this is a div okay so we start out with the blue class that we will need to toggle or remove and let's see what other class i possibly have that we could change it to oh black so it actually starts out black and then we'll change it to blue which is a little different than the dark blue so i save that and now when i click blue purple i'll click again back to black and dark blue now let's look at the h2 event listener we are changing the color so when i click the colors change back and forth with the toggle but we are not changing the click text so we start out with it saying my second view and that changes to click and right now it just stays so we could also have that toggle back and forth but we can't do it with toggle like we do with classes we actually need to look at what it equals and then set it to something else based on that now if then statements could do that also i will probably do this with a ternary statement so let's define our text first and i'll just say my text equals event dot target dot text content and so this will shorten this up a little bit so if my text equals my second view then we want it to result in equaling clicked but we can't just say clicked at that point we actually have to set the text content as well so then we say event dot target dot text content equals and we could say clicked at that point and then of course we have if it's not then it could be event dot target dot text content equals and now we want it to go back to my second view we'll save that and let's see if this works out for us and we click again and it goes back to my second view so now everything toggles that we've got set our text is toggling and both of our background colors are toggling and that is because we are using classes and we are toggling those classes on and off the class list for each of those elements let's now look at another event listener example and we'll just continue to add this inside our init app function so it adds the event listener after the ready state that we're looking for the ready state complete adds to our page and of course we've still got that noted over here in the console so what i'll do now is define a nav variable and as you might guess that's going to hold the nav element for the page and we have that at the top of the page just a nav bar that says my page so all we have to do is search for the nav element here with our query selector and then with the nav we will add an event listener and i'm going to put the mouse over and here comes the event as you might expect and it's an arrow function and so this is an anonymous function and we're listening for the mouse over event and once again we're going to use the class list say event target dot class list dot add and i have a class defined as height 100 and we will add that class to the nav element and let's look at that class real quick height 100 just changes the height to 100 pixels so now when we mouse over our nav element it will get 100 pixels instead of what it currently is and there you go just moused over we didn't even have to click so there are a a lot of events you can listen for and i'll put a link to the mdn page that documents those events below this video but once again this doesn't change back it has a height of 100 but then after i remove my mouse it still stays at that height let's see if we can toggle this one with the mouse over now i have mouse over and it's got a height of 100 and i remove my mouse and it stays 100. so ideally it would change back as soon as i remove my mouse but with the toggle and it's just listening for the mouse over i have to put my mouse over it again for it to change back and remove that class so the toggle isn't the exact behavior we're looking for here so let's change this back to an add and it's just going to add that class height 100 and it'll stay there so now let's add another event listener and this will be a slightly different event that we're listening for we've got the mouse over now let's listen for mouse out and this will be our mouse out event and now we'll say event.target.classlist dot remove and we will remove the class when the mouse out event occurs and so oh we have a syntax error malformed arrow function i have no comma and now everything looks as it should so now we mouse over and it grows and we mouse out and it goes back to the original size that is more the behavior we wanted okay before we finish working with event listeners i would definitely want to look at an html form because there is one thing about event listeners we haven't looked at yet and that is the prevent default so here i have the init app function cleared out we're still listening for this ready state to equal complete and we still have that in the console i have a very simple form defined here on our page and we're now working with view three that i've defined for the page and we've got that variable already and so now we want to get the form so i'll define my form set that equal to view three instead of the document since we've already assigned view three and now we'll say query selector and we'll look for the id my form that i assigned to the form on the page and then with that we'll add an event listener i'm going to listen for the submit function which is something a form does by default and now we'll do something inside of this event listener and at first we'll just log to the console submit event so we'll know when that is called i'll save this and now let's also do one other thing before we look at the console i'm going to inspect and get inside the form and you can see this is the input element and we have a button also in the form and a label and here's our form right there now when we type into an input we can just say hey if we hit enter because this form only has the one input it will fire the submit function but a form also wants to submit that information somewhere now i didn't set the form action at all you can see it just has an id or the method neither one of those attributes i just have a form element but it still has that default behavior so when i hit enter our text goes away and you see all of these elements flash because it really reloads the page and the same thing when i click the submit button it will do it by default and it just has that default form action and we don't always want that sometimes we want to prevent that from happening and that's definitely the case with modern javascript many times we want to prevent the default behavior of the form grab that information and then we want to see if the information is correct and then possibly use the fetch api to send that off to an api where we can save that information whether it's mongodb or a mysql database or wherever so let's take a look at how we can stop that let's come back to the console and let's see if we've got the submit event logging at all say hey yes it logs very quickly and then it disappears because the page reloads and then we get this again because we get that when it loads so we'll just see that event for a second let me go ahead and do this one more time i have hey and i'll hit enter and you see the submit event just flash over there and then it's gone so we really want to stop this from happening and so we'll put event dot prevent default and now we'll save that i'll type one or i guess i've been typing hey it doesn't really matter i'll hit enter now you can see the submit event logs it doesn't reload the page our words don't disappear here we've got another submit event when i click the button and then a third and i can hit enter and we get a fourth but the default behavior no longer happens we we don't get a flash of the page i'll go ahead and inspect and we can once again look at the elements over here and now when i hit enter they don't flash either so we have prevented that default behavior of the form and that is good to know because that will come in handy in an upcoming project that we work on hi i'm dave and i hope you enjoyed this tutorial remember to keep striving for daily progress instead of perfection subscribe to my channel and ring the bell to be alerted when i post new tutorials i'll see you next time
Info
Channel: Dave Gray
Views: 2,483
Rating: undefined out of 5
Keywords: event listeners in javascript, javascript event listeners, listening for event in javascript, javascript event listeners tutorial, event listeners, event bubbling, event capturing, event bubbling in javascript, event capturing in javascript, addEventListener, removeEventListener, event propagation
Id: UVRDq-wnfgk
Channel Id: undefined
Length: 39min 32sec (2372 seconds)
Published: Tue Oct 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.