← Back to Index

.on()

Attach an event handler function for one or more events to the selected elements.

Examples

1. Direct binding

$('button').on('click', function(e) {
     console.log('Clicked!', this);
});

Result

// Console Output on click:
"Clicked!" <button>...</button>

2. Delegated binding

$('#container').on('click', '.btn', function() {
     console.log('Button inside container clicked');
});

Result

// Events bubble up to #container.
// Handler runs only if target matches .btn.

3. Multiple events map

$('input').on({
     focus: function() { console.log('focused'); },
     blur: function() { console.log('blurred'); }
});

Result

// Handlers attached for both events.

4. Using namespaces

// Bind two click handlers
$('#myBtn').on('click', () => console.log('Regular click'));
$('#myBtn').on('click.myPlugin', () => console.log('Plugin click'));

// Later, remove only the namespaced one
$('#myBtn').off('click.myPlugin');

Result

// Initially, clicking the button logs both messages.
// After .off('click.myPlugin'), only 'Regular click' is logged.
// This prevents unintentionally removing other scripts' handlers.

Parameters

Parameter Type Description
eventType string | object One or more space-separated event types (e.g., 'click', 'submit keydown'), or an object of event types and handlers.
selector string A selector string to filter the descendants of the selected elements that trigger the event. If null/undefined, the handler is bound directly.
handler function A function to execute when the event is triggered.
options object Optional settings:
  • once (boolean): If true, listener is removed after first trigger.
  • passive (boolean): If true, indicates the handler will not call preventDefault().

Returns: The original SR object for chaining.