Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.2Binding events with jQuery

Part 3.2Binding events with jQuery

Events are an important part of any programming language that needs to be interactive. As such, JavaScript implements a variety of different events and the handlers to go with them. For instance, JavaScript defines onclick and onmouseover events and jQuery can work with these.

What an event is

An event is the response or the trigger when something else happens. Strictly speaking, the onclick is the event. Events are basically a method of interaction in JavaScript such that when an event is fired some event handler then responds.

JavaScript allows multiple handlers to be called when an event occurs. jQuery makes it even easier than raw JavaScript to attach multiple handlers to an event.

Often attaching these handlers to events is referred to as binding them. That's because once they are bound they do not need to be referenced any longer but as a result of this, it's not possible to stop them firing on the event directly.

Binding events

Binding an event is easy with jQuery is very easy. The first step is to select all the elements that are to be given the event and then running the bind on them.

JavaScript
jQuery("button").on("click", function (event) {
  //Do something
  alert("Button clicked!");
});
		

Run the code above and click the following button:

That's all there is to binding events to elements in jQuery. It's really so easy.

Binding universal events

There are on occasion times when an event needs to be universal and that all elements current and future are affected by the binding. In this case, jQuery provides a very clever system to bind an event to a selection of elements regardless of whether or not they are on screen at the time of binding. 

JavaScript
jQuery("#button_container button").on("click", function (event) {
  //Do something
  alert("Button clicked!");
});
		

By binding the event to the document, the document holds the event and the action is stored in a list of events. When an element is clicked the document's bound event is fired and allowing jQuery to lookup what action should be taken.

Run the code above and watch what happens.

Removing event handlers

So far this tutorial has covered adding event handlers to elements, but it has yet to show the jQuery way of removing event handlers.

Since jQuery has the on method, it also has the off method. This method will remove any bound event handlers on an element and works very similarly to the on method:

JavaScript
jQuery("#button_container button").off("click");
		

Numerous event handlers can be used with this such as dragon or hover much as they can with the on method.

Feedback 👍
Comments are sent via email to me.