QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Understanding Javascript Events In Depth

Understanding Javascript Events In Depth

javascript-events

In this post we will look a Javascript events in depth. You will learn what are events, what are different types of events, how events work, how to customize default actions, creating custom events, method of registering events and much more. Having a good understanding on Javascript events will help to develop better websites.


What is a Event?

Event is an action from user or program detected by the program. For example: click mouse button, key press, scrolling etc cause events.

What is an event handler?

A piece of code executed when an event occurs.

Event default handler

Browser assign a default handler for few events. This handler is executed after our specified event handlers is finished executing. For example clicking on an anchor link opens a new page. That’s the action done by the default handler. If we attach our click handler then that’s executed before default handler.

We can also stop default handlers from executing.

Different kinds of Javascript events?

Events that can be detected and handled using Javascript running in web browser is called as javascript events. Few different types of javascript events are:

  • DOM Events: Events fired due to some action on HTML elements. This can be mouse events, keyboard events, touch events, form events, frame events etc. For more info on DOM events follow this article
  • AJAX Events: Events caused during a AJAX request.
  • Window events: These events are for notifying window changes, connection availability, and many other things.
  • Custom Events: Events that are manually created and also called up manually are custom events.

There are many other kinds of events available for Javascript.

Registering event handlers using classic method

Let’s see how we can register event handlers for DOM events using classic method.

A HTML tag can be considerd as an object in Javascript. Objects have properties. Properties can point to functions. So we can create a function for handling a particular event and then assign it to the property for that particular event.

We can assign HTML properties using javascript or on the HTML tag itself.

Now when we click on the first or second button the browser checks if onclick property is assigned or not. If it is then it fires the attached function.

Both the above ways are same, its just different way of assigning a handler to the onclick property.

Here we can see that javascript is executed after the HTML code for button executed. So javascript override’s the onclick property.

For non DOM events, we need to assign handlers using javascript only.

This is an example of handling window.onload event using classic method.

The disadvantage of using classic method is that we can assign only one handler to a particular event.

Registering event handlers using addEventListener method

We can also register events using addEventListener method. addEventListener doesn’t override event property instead it uses some internal techniques to call the assigned handlers for a particular event.

It takes three parameter. First one is the event name, second is a callback which will be fired when event occurs and finally a boolean value indicating whether the event comes under bubbling or capturing (we will see bubbling and capturing later in this post).

In the above code we registered an event handler using addEventListener method.

Let’s register event handler for HTML load event (window.onload) using this new method.

The advantage of using this method is that you can register multiple handlers. And also you can control bubbling and capturing of events.

Let’s create multiple handlers using this new method

Handlers were called in the order they were assigned.

Using both classic method and addEventListener method

You can see that they both don’t come in each other’s way. They are called in the way they are registered.

Cancelling Default Handler

Default handler is always executed after the defined handlers are executed. You can disable the default handler.

If you are using classic method of creating event handler then returning false will prevent the default action. But if you are using addEventListener then calling e.preventDefault() will cancel default handler.

Be careful while using return false as it will also cancel event propagation also.

Event Propagation

When you click on an HTML element then all of its parent elements along with it receive a click event.

For example:

Div 1

Div 2

In the above example when you click the inner div and you will see that outer div also receives a click event. This is what called as event propagation.

But how can you decide whether the inner element will receive event first or outer element. This is called ordering of event propagation.

There are two types of event order: capturing and bubbling. In capturing, the outer element will receive event and then the inner element. But the opposite happens in bubbling.

Whenever an event occurs both capturing and bubbling occurs. During capturing browser travels from parent to child to check if any event is registered under capture. Those matching events are executed and then it bubbles again. During bubbling it checks if any event is registered under bubble. If it find any then it executes them.

Capture

Therefore we can order our events by assigning them to bubble or capture.

Event handlers as bubbling or captureing

Let’s see how we can register our events for bubbling. So that during capturing no event is called but during bubbling events are executed.

When we registers handlers using classic method, all the events are registered under bubbling phase. So inner events will be called up before outer events.

When we register handlers using addEventListener(), we have the choice to choose whether a handler comes under bubble or capture phase. If the last parameter is true then it comes under capturing and if its false then bubbling.

Div 1 and Div 3 click events were registered under capture phase so they were executed first in order top to down. And then During bubbling Div 2 click event was executed.

Stopping Propagation

Event propagation can be stopped using two ways: returning false in classic method or using stopPropagation() in addEventListener() method. As soon as one of this is called the propagation stop there.

Here Div 1 click event is registered under capture phase. So first its handler is executed (top to bottom) and it calls stopPropagation(). Therefore capturing and bubbling stops there.

You can learn more about event propagation from this link.

Creating custom events

There are two ways of creating custom events: classic method and using addEventListener(). If you created custom events then you have to call them manually.

Let’s see the classic way of creating events:

Creating event in the newest way:


Conclusion

Always try to use addEventListener whenever possible. Try to stick with capturing or bubbling don’t mix them up. So that your code is simple and easy to debug. There is always more to learn. I will keep updating this post as I will find new techniques and theories. Thanks for reading. If you like it please share it.

Apr 13, 2014Narayan Prusty
Creating A Page Load IndicatorCreating A Viewport Resizer
Comments: 1
  1. Gazal Garg
    6 years ago

    Great explanation. Thank You!
    Can you please replace (almost) all usage of ‘than’ with ‘then’ in your article. It just kills the flow, momentarily.

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 2 Comments Web Developmentevents, javascript, javascript events
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • What is a Event?
  • What is an event handler?
  • Event default handler
  • Different kinds of Javascript events?
  • Registering event handlers using classic method
  • Registering event handlers using addEventListener method
  • Using both classic method and addEventListener method
  • Cancelling Default Handler
  • Event Propagation
  • Event handlers as bubbling or captureing
  • Stopping Propagation
  • Creating custom events
Related Articles
  • requestAnimationFrame Tutorial
  • Monitoring and Intercepting all AJAX Requests
  • Detecting If Browser Is Online Or Offline Using JavaScript
  • Exit-Intent using JavaScript
  • Launch Browser Inside Intel XDK App
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license