Start a team blog
Start a team blog, invite your team, and start publishing.

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

Event Delegation: A practical, fun example

timothy ogbemudia's photo
timothy ogbemudia
·Jul 30, 2019

<span class="l"></span>

Event Delegation: A practical, fun example

<noscript><img alt="web development photo" src="miro.medium.com/max/2000/0*_huskDP-ErOnrnit" class="em n o el z" width="1000" height="667"/></noscript>

Photo by Shahadat Shemul on Unsplash

First off I want to start off by apologizing to any 10x JavaScript engineers if I’m slighty off in my explanation I’ve only been doing JavaScript since February, that said this kinda “practice by doing” article is targeted at beginners and people fairly new to JavaScript like I am.

So for some context as to why I even got the idea for this article: there I was at home watching my React course on Udemy then the WiFi became a bit iffy and I couldn’t carry on so I decided what the heck ? I might as well continue with a very small project now there I was faced with a challenge and after perusing my brain the answer lay in event delegation.

So consider this scenario: you want to do something with an element on the page, say a button you inserted with JavaScript or just was not there on page load, you attach an event handler,do your logic but oops it isn’t working, that’s odd, it should, shouldn’t it? WRONG and here’s why and hopefully never forget- IT DOES NOT EXIST ON THE PAGE.

What I mean is when the page loads, that button is not part of the HTML loaded on the page and you can only access elements that are on the page well that’s where event delegation comes in, with event delegation you can perform operations on elements that weren’t on the page on page load. Don’t believe me? log it to the console, you’ll see a null error.

Whew that was a lot of talking, let me now show you a fun example of event delegation and using the e.target.matches function. So what we’ll do today is basically show a few movie quotes onClick. So copy and paste all the gists below in your favorite text editor. Don’t worry if the JavaScript seems a bit “advanced” I’ll take my time to explain thoroughly.

<iframe src="medium.com/media/8f1372a378ae20c8f6a7e91933.." frameborder="0" height="0" width="0" title="index.html" class="em n o el z"></iframe>

So quick explanation we simply have a HTML doc, nothing fancy a few links to style.css and a really cool font from Google fonts to try and make the page look nice. Onto the styling.

<iframe src="medium.com/media/e216512b634a3a525ac5682211.." frameborder="0" height="0" width="0" title="style.css" class="em n o el z"></iframe>

Here we do some basic styling to make the page look a little less dull and basically here just style the a tag or button to make it prettier. You can chop and change and add more as you wish. Now onto the JavaScript

<iframe src="medium.com/media/cb3ead04a6ad98624022864913.." frameborder="0" height="0" width="0" title="app.js" class="em n o el z"></iframe>

So here we attach an event listener to the button and we log “working” to the console to ensure it’s working. (it’s sensible to log something to the console for testing purposes). All right now for the markup we use a template literal aka backticks instead of quotation marks and the reason is with quotation marks you would have to define all your HTML markup in one long string with NO SPACES and that really is stressful honestly so with backticks it’s spread over multiple lines. Pay attention to the a tag / button, we will need that specifically as we target that for the event delegation, we stylishly add a new class btn on there.

Next we have to remove the button from the DOM with button.parentElement.removeChild(button) , we don’t have to as if we comment it out it still gets removed from the DOM via the next line but i’d like to show you how to remove from the DOM. That’s just the syntax I really cannot explain why we have to do it like that but I intepret is as “go up to my parent element and then remove me from the DOM”.

Now if you’ve never used insertAdjacentHTML I’ll leave a link below to the MDN docs but basically it allows us insert into the DOM at any element we chose and any markup. It’s far superior to innerHTML simply because you can decide position you want it to be inserted. So finally we’re through with that part. Now for the real magic.

<iframe src="medium.com/media/da6fa4d26033f714af24403260.." frameborder="0" height="0" width="0" title="app.js" class="em n o el z"></iframe>

Now what we’re trying to do is we want to display some quote every time we click a button, not several just one .It’s bad UX in my opinion to have several simply because does the user then have to scroll to the next button for every quote imagine if you have 15 so 15 sections?.

So first off we listen on the window object for ANY CLICK and pass in the event object. I chose to log the element with the btn class so you see it returns null. I also log e.target.matches which returns true or false. Now event.target.matches simply returns true of false if an event occurred on an element you specified via classname. So in our case and since we’re listening globally we mean “if we click anywhere on the page does the element we click match the element passed into the function?” at least that’s how I understand it.

Everything else is straight forward we simply do an if check and if it’s true we then basically apply the same logic again except now we clear the whole grab-div element instead of what we did above, which as I said was just so I could show you how to remove from the DOM.

So that’s basically it. As a challenge to whoever’s reading this add a few more of your favorite movie quotes on your own to really get it under your fingers, rewrite this whole thing, and hey you could even add a little ending “made with heart emoji by your name” as your last quote to really personalize it. I’ll add a link below on how to use emojis on Windows and also via ionicons which is a favorite of mine.

If you enjoyed my tiny contribution to the JavaScript world please give it a clap and share with others.

[## Element.insertAdjacentHTML()

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the…

developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML?source=post_page---------------------------) [## Event.target

The target property of the interface is a reference to the object that dispatched the event. It is different from…

developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/API/Event/target?source=post_page---------------------------) [## Ionicons: The premium icon pack for Ionic Framework

Ionicons is an open-sourced and MIT licensed icon pack.

ionicons.com](https://ionicons.com/?source=post_page---------------------------) [## How to use Emojis in Windows 10

No chat conversation is complete without the colorful and interesting Emojis or the Emoticons. While almost every…

thewindowsclub.com](https://www.thewindowsclub.com/emojis-in-windows-10?source=post_page---------------------------) [## Removing an element from the DOM with vanilla JS

Yesterday, I showed you how to inject elements into the DOM. Today, let's look at how to remove them. There are two…