📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials jQuery in Practice Events

Events

5 min read Quiz at the end
Attach event handlers with on('event', handler). Use off() to remove them and one() for handlers that run only once. on() is the recommended method — shorthand methods like click() are less flexible.

Event Handling

// Attach event
$('#btn').on('click', function() {
  alert($(this).text());
});

// Multiple events
$('input').on('focus blur', function() {
  $(this).toggleClass('active');
});

// Remove event
$('#btn').off('click');

// One-time event
$('#btn').one('click', fn);
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which method attaches an event handler?
💡 .on() is the recommended method to attach event handlers in jQuery 1.7+.
2. Which method removes an event handler?
💡 .off() removes event handlers attached with .on().
3. Which method fires an event only once?
💡 .one() attaches a handler that fires only the first time the event occurs.
4. How do you trigger a click programmatically?
💡 Both .click() (shorthand) and .trigger('click') programmatically fire the event.
5. Which event fires when the mouse leaves?
💡 .mouseleave() (or 'mouseleave' event) fires when the cursor leaves an element.