JavaScript Tip: Event Registration

JavaScript normally runs code sequentially, which means in the order that the browser reads it from your file, but we can write JavaScript code that will run only when something happens in the browser. That’s because browsers can trigger events, when things happen to elements on your page.

When the page loads in a browser, when the user moves the mouse over a link, when a video has finished loading, or when a form is submitted are events. So if you want to take care of a task when something happens you have to capture that event, and that’s done through a process called event registration.

This means telling the browser that you want to do something when an event takes place, and there’s several ways of doing that. Some are more compatible with older browsers than others.

The first (but legacy) way of doing this is by using tag attributes, and this works pretty simply.

Now this is considered extremely bad practice, because it makes your code hard to update. It’s much better to place the JavaScript outside the html tags, so you can also check for events by attaching them to a specific element. Using dot notation in your JavaScript code. It means that you first specify which element in the dome you want to get to, and then specify which event you want to track.

The more modern way of handling events is to use a special method called addEventListener. You can use this method on any element in your page. It asks for the type of event, a function and a third true or false value called the propagation type.

The advantage of using addEventListener is that it allows you to check for multiple events within a single call (called event propagation).

Note: addEventListener is not supported by IE8and older browsers, so using a framework like jQuery is used for legacy browser support is required.

Leave a Reply

Your email address will not be published. Required fields are marked *