We’ll cover the following:
- Template literals
To understand this more clearly, let’s build on our traffic light analogy. Think of an event handler as a traffic cop at an intersection. The cop waits for certain events, such as a car running a red light, to take an action that is a response to that event, such as writing the driver a ticket.
Event handlers vs. event listeners
- Inline event handlers
- Traditional event handlers
- DOM level 0 event handlers
Let’s take a look at each of the handlers above to understand what functionalities they provide.
Inline event handlers
Inline event handlers can be added directly to the HTML element using the
on attribute. The main benefit of using inline event handlers is their simplicity. Some examples of inline events are:
onclick: This event is triggered when the HTML on which it is attached gets clicked by the user. This event handler executes the code specified in its attribute
onsubmit: This event handler is triggered when a form is submitted. It also executes the code specified in its attributes
onmouseover: This event is triggered when the user moves their mouse on the element on which it is attached
Traditional event handlers
Traditional event handlers are used in web development to attach event listeners to HTML elements. As every browser supports them and they have been in use for very long, their main benefit is their compatibility and flexibility.
Some of the traditional event handlers are:
onkeydown: This event is triggered and the code is executed when the user presses the down key on their keyboard
onscroll: When a user scrolls through an HTML document, this event handler triggers the function
onload: When all the resources of the HTML page are loaded, this event is triggered
DOM level 0 event handlers
DOM level 0 event handlers refer to the traditional approach that was used during the early days of the web. During this approach, we simply used to set a property on an HTML element that usually corresponds to the name of the event we want to listen for, and then we assign a function to it that gets called after the event occurs.
Some of the DOM level 0 event handlers are the same as what we have already discussed. The only difference is the way they get attached to the HTML code is different. DOM level 0 event handlers include:
onload: This event is triggered when a webpage has finished loading
onmouseout: This event is triggered when a user moves their mouse out of an element
onsubmit: This event is triggered when a form is submitted
When an event is triggered, there are three phases that the event flows through the DOM (Document Object Model). These phases are the capture phase, target phase, and bubbling phase.
During the capture phase, the event first moves from the top of the DOM hierarchy towards the target element.
After the event reaches the target element, it triggers the event listener attached to that element. The target phase is the phase where the event actually happens.
After the target phase, the event bubbles up from the target element towards the top of the DOM hierarchy. It’s important to note that not all events go through all three phases. Some events only have a target phase, while others may skip the capture or bubbling phase. It depends on where the event was triggered.
More great articles from LogRocket:
- Don't miss a moment with The Replay, a curated newsletter from LogRocket
- Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
- Use React's useEffect to optimize your application's performance
- Switch between multiple versions of Node
- Discover how to animate your React app with AnimXYZ
- Explore Tauri, a new framework for building binaries
- Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
In the example above, the
btn class does not exist in our
index.html page. Therefore, this will throw an error of
addEventListener of null.
document.createElement() method allows us to create the HTML elements by their tag names, like
When we create an element with
We’ll dynamically create our elements, inject it to the DOM, and also attach event handlers. Follow the link to the live CodePen demo:
Here is our
In our index.js, we used
document.createElement() to dynamically create a new
div. Then, we added a dog class to the
div we created earlier.
classList property is used to add, remove, and toggle CSS classes on an element. Next, we created an image tag with
alt attributes. We also created the
h2 tag and added text contents in it. Then, we added a new
p element with a class of
info that will contain more information about the dog.
Next, we’ll dynamically create a button with a class of
btn. We’ll add text saying
click here to read more. If you inspect your browser, you won’t see the
div with a class of
dog we created because we haven’t appended it yet to the DOM.
Now, we’ve dynamically created an element. The next question is: how do we inject it to the page? To inject it into the DOM, we are going to use the
.appendChild() method to append the dynamically created elements.
If you inspect your console, you will see the dynamically created elements injected in your DOM. Now we can add event handlers. To attach event handlers to the dynamically created button, we need to select the button with a class of
btn and add an event listener of
We’re saying that
onclick of the button, the
p tag with a class of
moreInfo should display
block. Here is the CSS code for styling the dog profile:
Check out this live demo at CodePen. Below is the screenshot of the dog profile before triggering the event that will happen after Click to read more about me is clicked:
Below is the screenshot of the site after the event gets triggered. Notice the difference, and observe how triggering the event transforms the DOM and reveals a new dev that was previously hidden and has text inside of it:
In the template
literals.js file, we declared
newDog, and use template literals to create multiple elements in it. If you
console.log(newDog), you will see the element created like a string in the console. Or, if you
console.log(typeof newDog), it is going to return a string showing that it is not yet a DOM element.
Next, we are going to use
document.createRange() to turn the string into a DOM element. Then, we call the
createContextualFragment() method that leaves on the range. When you
console.log myFragment, you will see a range of objects (a collection of elements, or part of HTML we can work with). Then, we append
myFragment to the body of the page.
N.B., If you need to do things like add event listeners or change classes, we should put it in the DOM with a
createcontextual fragment and then put it in the body or anywhere else in the page.
Next, we are selecting the button with a class of
.btn where the users click to read more about the dog. If you
console.log(btn), you find out that it is in the DOM because we have injected it to the DOM through the
Adding event handlers
We added an event listener of
click, and called a
showMore function. In the
showMore function, we selected the class
moreInfo. If you check on our
css you find out that the text was set to display none. So now we are saying that
onclick of the button, let the display
none change to display
Congratulations! Our dog profile is complete. All elements were created dynamically, and the event handler of
onclick was added to the dynamically created elements.
document.createElement and template literals. We also conveyed the different approaches that one can take while writing an event listener. Remember that each approach has its own pros and cons.
Debugging code is always a tedious task. But the more you understand your errors the easier it is to fix them.
Thanks for the content. He helped me a lot.