DEV Community

Bevin Duncan
Bevin Duncan

Posted on • Updated on

'Splain Like I'm Five: JavaScript Events

It is safe to say that the heart and soul of any effective web page is the ability for a user to functionally interact with the contents of that web page. Being able to click on, scroll through, or input information through a web browser is fundamental to the usability of most modern-day web applications--from social media, to banking, to learning software engineering through an online bootcamp. But what exactly is going on under the hood when you click that like button, anyway? The answer to that question is: A JAVASCRIPT EVENT!

Javascript events describe a multi-process coding cycle that involves three major components: HTML Elements, Event Listeners, and Event Handling Functions. Let's dig in to how these three components work together to create an enriching, interactive experience for your user!

HTML Elements and the DOM
As you may know, the elements you see on a web browser are structured by HTML. Each HTML element has a specific purpose in the HTML document, and therefore the structure of the web browser. For example, if you'd like to add a "like" button to your page you would first craft its structure in the HTML document as an element. However, these HTML elements are static unless we use javaScript to animate them, which are then rendered in the DOM.

Javascript Event Listeners
Unless you use javaScript to tell the browser what to do with that "like' button once its clicked, that like button will be nothing more than a fancy icon decorating your browser with no real functionality. So how do we create a line of communication to the HTML document to animate our like button? Luckily, javaScript has a built-in system for "listening" for events! Simply put, an "event listener" is a built-in javaScript command that links an HTML element to the event you would like to have happen. This is done in three steps:

  1. "Grabbing" the HTML element from the document with a query selector and attaching it to a constant variable.
const likeButton = document.querySelector("button"); 
Enter fullscreen mode Exit fullscreen mode
  1. Linking that constant variable to the event you would like to enact using .addEventListener().
likeButton.addEventListener("click", );
Enter fullscreen mode Exit fullscreen mode
  1. Referencing the "Event Handler" function in the event listener that will ultimately enact the event we want once it's called.
likeButton.addEventListener("click", handleLikeButton);
Enter fullscreen mode Exit fullscreen mode

Event Handlers
Hold up, we referenced an event handling function with the event listener we just learned about! What's going on there?? The "event handler" is an important piece of this puzzle, because we need to tell our program what to do with the 'click' we just assigned in our listener using a function. An event handler is a callback function that indicates to the listener what the outcome of the event will be. For example:

function handleLikeButton(){
  likeNumber.textContent = ++likes
}
Enter fullscreen mode Exit fullscreen mode

In the above case, we've created a function that incrementally (++likes) increases the displayed (text content) number of likes (likesNumber) on our page! The event handler dictates the outcome of the event. The handler is called by the event listener--which links it to the 'click'--and increases the likes once the click is initiated.

Here's visual of how the components of the javaScript event cycle work together:

Image description

Types of Events
As you can imagine, click events are one of many, MANY javaScript events that can be applied to a webpage. Other common events include:

Mouse events: Any interaction having to do with mousing over, in/ out of, or clicking on an element.

Keyboard Events: Any interaction having to do with key presses of any kind.

Submit Events: Events pertaining to inputting and submitting values to forms.

Screen Sizing Events: Events that occur when resizing or scrolling through the browser window.

And many more.

Event Objects
Event objects are a way for you to call on the event in a handler as a parameter. Common usage for this would be to change specific properties of the event target (In our case, the LikeButton variable we grabbed from the HTML sheet):

function handleLikeButton(e){
   console.log('e: ', e.target);
    } 
Enter fullscreen mode Exit fullscreen mode

The target property of the event object is a reference to the element the event occurred upon. So, in the above example, we are logging the content of our like button to the console. Other uses for this method would be to modify the qualities of the event target (like the color or text content), or to link the event target to a database object (and many more). Event objects can be labeled in any way, but conventionally they're labeled "e", "evt", or "event" because they're short and easy to remember, plus it's always good to be consistent in shared code.

Bubbling and Capturing
Sometimes you'll want to link an event listener to a parent node that oversees multiple HTML elements with their own events. This can be super handy, like when we have lots of buttons on one page nested under the same parent node and only want to take the time to write out one event listener, or to link multiple events under the same parent node.

"Capturing" is a phase in the DOM's order of operations where the browser reads our code from the outermost layered node in the DOM tree, to the innermost. In this phase, the browser is "listening" for events starting from the top down.

"Bubbling" is essentially the opposite of the capturing phase, and starts at the time the event is triggered. The inner-most nested node is triggered first, then its parent node, grand parent node, and so on all the way back to the top of the document. If events are linked to these respective nodes the events will be triggered in order from the innermost nested event out to the top. It's important to note that modern browsers handle events in the bubbling phase by default.

Here is a diagram of the Capture/Bubble cycle:

Image description

You can read more about the Capture/Bubble cycle here.

Stop Propagation
There are times where bubbling can be detrimental to to the functionality of your page. One scenario is when two events firing in tandem with each other negatively effect the outcome of one or all of the events. Luckily, there's a way to "stop the propagation" of the bubbling phase! It's called, naturally, ".stopPropagation()".

Best practice is to call .stopPropagation() on the event object in your event handler, which will stop the bubbling phase at the time the event is called. When invoked on a handler's event object, .stopPropagation() makes it so that first handler is run but the event doesn't bubble any further up the chain.

An example of .stopPropagation() syntax:

likesBttn.addEventListener("click", function (event) {
    event.stopPropagation();
    likeNumber.textContent = ++likes

  });
Enter fullscreen mode Exit fullscreen mode

Prevent Default
A default action of a submit form event is to reload the browser. In some cases, we want to prevent that default action. Luckily, javaScript has a built-in command to deal with this issue: .preventDefault(). Having this command included in your event handler function creates a catch-all scenario for those circumstances when you don't want the browser to automatically refresh the form.

Here's an example of .preventDefault() syntax in the context of a form event:

function handleReviews(e){
  e.preventDefault()
  let reviewLi = document.createElement('li')
  reviewLi.textContent = `${reviewInput.value}

  e.target.reset()
};
Enter fullscreen mode Exit fullscreen mode

In the above example, we've created an event handler that handles a form for users to add new reviews to our page! The event object is referenced, then we use dot notation to add the preventDefault() command to it. The rest of the code displayed here allows us to add a new HTML element with our users new review to the DOM, and reset our review form input fields for the next user!

Conclusion
Events are hugely important to creating an interactive, functional web page. The options for how to deploy events and their handlers are endless, and there are many "best practices" to look for when planning your event cycles, depending on what events you'll be including on your page. Events exist in many coding languages and javaScript is only one of many iterations of this process in the field! The more you learn about events--and there is much, MUCH more to learn!-- the more empowered you'll be to make effective, functional, interactive web applications to attract users.

Happy eventing!

Resources

Top comments (0)