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

html
<button id="myButton">Click Me</button>
<p id="message"></p>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(
'#myButton').click(function() {
$('#message').text('Button was clicked!');
});
</script>


Using .on() to Attach Events (Recommended)

.on() is more flexible and can attach multiple event types or delegate events for dynamically created elements.

js
// Attach click event
$('#myButton').on('click', function() {
alert('Clicked!');
});

// Attach multiple events
$('#myButton').on('mouseenter mouseleave', function(event) {
if (event.type === 'mouseenter') {
$(this).css('background-color', 'yellow');
} else {
$(this).css('background-color', '');
}
});


Event Object

Inside event handlers, you often get an event object giving info about the event (like which key was pressed).

js
$(document).keydown(function(event) {
console.log('Key pressed: ' + event.key);
});

Prevent Default Behavior

Sometimes you want to stop the default action (like following a link):

js
$('a').click(function(event) {
event.preventDefault(); // Stops the link from opening
alert('Link clicked, but no navigation!');
});

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.

Leave a Reply

Your email address will not be published. Required fields are marked *