Attach an event handler function for one or more events to the selected elements.
$('button').on('click', function(e) {
console.log('Clicked!', this);
});
// Console Output on click:
"Clicked!" <button>...</button>
$('#container').on('click', '.btn', function() {
console.log('Button inside container clicked');
});
// Events bubble up to #container.
// Handler runs only if target matches .btn.
$('input').on({
focus: function() { console.log('focused'); },
blur: function() { console.log('blurred'); }
});
// Handlers attached for both events.
// 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');
// Initially, clicking the button logs both messages.
// After .off('click.myPlugin'), only 'Regular click' is logged.
// This prevents unintentionally removing other scripts' handlers.
| 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:
|
Returns: The original SR object for chaining.