To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

Binding events with jQuery3.2

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(document).on("click", "button", 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 when the code below is executed and creates a new button:

 
JavaScript
var btn = document.createElement("BUTTON");
btn.innerHTML = "Click me";
jQuery("#button_container").append(btn);
		
Feedback 👍
Comments are sent via email to me.