The on() method is commonly used in JavaScript to attach event handler callbacks to HTML DOM elements. It allows executing a JavaScript function when a particular event occurs on a selected element.

Although not a native browser API, on() is defined and implemented in popular JavaScript libraries and frameworks like jQuery, Node.js, React, Angular, etc.

This comprehensive guide will explain how the on() method is defined, why it is useful, and provide several real-world examples of how to use it for event-driven web programming.

What Does the on() Method Do?

The on() method binds an event handler function to the selected DOM elements. It attaches the supplied callback to handle the specific event when triggered on the selections.

For instance, the click event handler attached via on() would execute when any of the selections is clicked by the user.

Some common examples are:

  • Run code on click event
  • Handle form submission on submit
  • Do validation on keydown
  • Show popup on mouseenter
  • Make AJAX call on change event

This allows running JavaScript code in response to user events like clicks, hovers, key presses for interactive web apps.

Signature and Syntax

The typical syntax signature accepted by the on() method is:

$(selector).on(eventName, eventHandlerCallback) 

Where:

  • $(selector) – jQuery selector for DOM element(s) to attach handler to
  • eventName – Name of the event to listen for (click, hover, etc)
  • eventHandlerCallback – Callback function to run when event occurs

When the specified eventName like "hover" occurs on any of the matched selector elements, the browser triggers the eventHandlerCallback, allowing developers to execute custom logic.

Relationship With addEventListener()

While both on() and native addEventListener() API can attach event handlers, there are some key differences:

  • on() is defined in libraries like jQuery, while addEventListener is a web standard
  • on() provides easier shorthand syntax and chaining with other methods
  • this keyword inside handlers references different objects
  • on() supports jQuery selectors, while addEventListener() works on individual DOM elements

So on() simplifies event binding through selector and chaining support. But addEventListener() offers better performance by working closer to the metal.

Event Propagation and Event Bubbling

The concept of event propagation is key to understanding how on() attaches handlers to trigger callbacks.

There are two ways events propagate in DOM:

1. Event Bubbling

This is the default mode for events. When an event occurs on a DOM element, it first runs the handlers on it, then on its parent, then all the way up to other ancestors.

Image source: https://www.javascripttutorial.net/

This propagating up from child to parent is called event bubbling.

2. Event Capturing

In this mode, event is first captured by the outermost ancestor and propagates down to the target element. Parents handles event before children.

The event capturing mode is rarely used.

Leveraging Event Bubbling

The on() method heavily utilizes this bubbling behavior to simplify code.

You can attach single handler to a parent that triggers even for events happening lower down on any children elements:

// Handle click for all children buttons 
$(‘.buttons‘).on(‘click‘, doStuff); 

This event delegation via bubbling eliminates need to bind callback separately with each child button.

Defining on() Method in Different Environments

The on() method is defined in various popular JavaScript libraries and frameworks:

1. jQuery

The on() method is defined globally in jQuery library:

// Pull in jQuery library
<script src="jquery-3.6.0.min.js"></script>

// on() is now usable
$(document).on(/* params */); 

2. Node.js EventEmitter

In Node.js backend, the on() method is defined on EventEmitter class to listen to events:

// Import EventEmitter class  
const EventEmitter = require(‘events‘);

// Create Emitter instance
const emitter = new EventEmitter();  

// on() is available via emitter
emitter.on(‘start‘, () => {
  console.log(‘Started‘);
});

3. React.js

In React applications, onClick() and onChange() act as handlers for JSX elements:

function Button() {
  // Attach click handler 
  function handleClick() {
    console.log(‘Clicked!‘);
  }

  return <button onClick={handleClick}>Click me</button> 
}

So React uses conventions like on<Event> for consistency.

4. Vue.js and Angular

Vue and Angular also use directives like v-on and (click) respectively to declare event listeners that invoke callback expressions.

Real-World on() Usage Examples

Let‘s explore some practical examples of how to use JavaScript‘s on() method in web programming:

1. Run Code on Button Click

The most common example is to trigger an alert on click event:

$(‘#myButton‘).on(‘click‘, () => {
  alert(‘Button Clicked!‘); 
});

Here the click handler runs each time #myButton is clicked.

2. Handle Form Submission

Run validation or send data on form submit event:

$(‘#loginForm‘).on(‘submit‘, (event) => {

  // Prevent actual submit
  event.preventDefault();

  // Form processing logic
  const email = $(‘#emailInput‘).val();

  console.log(`Submitted email: ${email}`);
});

3. Validate Input Field

Attach data validation on keydown event:

$(‘#ageInput‘).on(‘keydown‘, (event) => {

  const age = $(‘#ageInput‘).val();

  // Validation logic
  if(isNaN(age)) {
    alert(‘Enter a valid age!‘);
    event.preventDefault(); 
  }

})

4. Show Popup on Mouse Enter

Display popup when mouse enters element:

$(‘#member‘).on(‘mouseenter‘, () => { 

  // Show popup
  displayPopup();

})

5. Make API Call on Select Change

Trigger AJAX request to fetch data on dropdown change:

$(‘#citySelect‘).on(‘change‘, () => {

  const city = $(‘#citySelect‘).val();  

  // Make API call
  fetchWeather(city);

})

These demonstrate some of the common real-world uses of the on() method for event handling.

Browser Support and Statistics

Event handling is a crucial part of interactive web applications.

As per StatCounter GlobalStats data below, JavaScript library jQuery with on() method usage dominates websites with 88.32% share among sites using jQuery vs vanilla JavaScript.

Image source: StatCounter GlobalStats – Browser Version Market Share

This proves on() is already supported out-of-the-box in 88%+ of sites for unified event binding thanks to jQuery. No need for cross-browser fixes.

The latest Chrome, Firefox, Edge and Safari work perfectly with on() method. Some key stats:

  • Chrome – 63.58% global share
  • Firefox – 3.59%
  • Safari – 18.58%
  • Edge – 2.98%

So overwhelmingly websites can use on() for robust event handling support.

Comparison of Frontend and Backend Usage

We saw how on() method can be used to handle events in frontend as well as backend JavaScript:

Frontend/Client-side Programming

The on() method sees heavy usage in frontend frameworks like jQuery, React, Vue and Angular for binding user-related event callbacks:

  • Click
  • Hover
  • Scroll
  • Type

It enables creating highly interactive interfaces responding to user actions.

Backend/Server-side Programming

In backend Node.js, the on() method attaches callbacks for server-related events:

  • HTTP requests
  • Database events
  • File system events
  • Network events

It allows scalable event-driven architectures using Node‘s EventEmitter pattern for I/O handling.

So while the method signature remains similar (on()) across environments, the use cases differ depending on frontend or backend programming.

Advantages of the on() Method

Let‘s recap some of the major benefits of using on() for binding event handlers:

πŸ’‘ Simpler Syntax

Just specify selector, event and callback instead of direct DOM event attributes manipulation

πŸ”— Chaining Capability

Enables cleaner code by chaining on() with other methods thanks to returned selection

πŸ•ΈοΈ Event Delegation Support

Attach single handler for events happening lower down DOM tree to reduce code

βœ… Cross-Browser Normalization

Abstractions inside on() handles browser quirks/inconsistencies

πŸ“¦ Reusability

Define handler logic in reusable functions instead of embedding inside HTML

πŸš€ Performance

Optimized handling compared to traditional DOM event features in older IE

Thanks to these advantages, on() offers great convenience and flexibility for scalable event binding.

Conclusion

The on() method is the ubiquitous idiomatic way for attaching event callback handlers across modern JavaScript ecosystems.

Whether it is jQuery‘s slick API in frontend web apps, or NodeJS‘s EventEmitter pattern in backend services, on() powers event-driven programming for responding asynchronously to notifications.

With robust browser support thanks to jQuery adoption, and simpler imperative syntax compared to old-school declarative event attributes, learning to use JavaScript‘s on() method is a must for both full-stack and frontend developers.

Similar Posts

Leave a Reply

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