jQuery Events: Responding to User Actions
Events are actions that happen in the browser, like clicks, key presses, mouse movements, and more. jQuery makes it super easy to listen for and react to these events.
Common jQuery Event Methods
| Event | Description | Example Selector & Event |
|---|---|---|
.click() |
Triggered when an element is clicked | $('#btn').click(function() { ... }) |
.dblclick() |
Triggered on double-click | $('#box').dblclick(function() { ... }) |
.mouseenter() |
When mouse pointer enters element | $('.item').mouseenter(function() { ... }) |
.mouseleave() |
When mouse pointer leaves element | $('.item').mouseleave(function() { ... }) |
.hover() |
Shorthand for mouseenter + mouseleave | $('#btn').hover(enterFn, leaveFn) |
.keydown() |
When a keyboard key is pressed | $(document).keydown(function(e) { ... }) |
.keyup() |
When a keyboard key is released | $('#input').keyup(function() { ... }) |
.submit() |
When a form is submitted | $('#form').submit(function(e) { ... }) |
.focus() |
When an element gains focus | $('input').focus(function() { ... }) |
.blur() |
When an element loses focus | $('input').blur(function() { ... }) |
Basic Example: Click Event
Using .on() to Attach Events (Recommended)
.on() is more flexible and can attach multiple event types or delegate events for dynamically created elements.
Event Object
Inside event handlers, you often get an event object giving info about the event (like which key was pressed).
Prevent Default Behavior
Sometimes you want to stop the default action (like following a link):
Summary
-
jQuery events let you listen for user interactions.
-
You can respond to clicks, keyboard actions, form submissions, and more.
-
.on()method is the most powerful and flexible way to attach events.
