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?
A. .bind()
B. .event()
C. .on()
D. .attach()
💡 .on() is the recommended method to attach event handlers in jQuery 1.7+.
2. Which method removes an event handler?
A. .off()
B. .unbind()
C. .detach()
D. .remove()
💡 .off() removes event handlers attached with .on().
3. Which method fires an event only once?
A. .once()
B. .single()
C. .one()
D. .first()
💡 .one() attaches a handler that fires only the first time the event occurs.
4. How do you trigger a click programmatically?
A. $(el).fire('click')
B. $(el).click()
C. $(el).trigger('click')
D. Both b and c
💡 Both .click() (shorthand) and .trigger('click') programmatically fire the event.
5. Which event fires when the mouse leaves?
A. mouseout
B. mouseleave
C. exit
D. leave
💡 .mouseleave() (or 'mouseleave' event) fires when the cursor leaves an element.
Submit answers