jQuery Events
An event is something that happens on the page: a click, a key press, a form submit, a mouse move. With jQuery you can run your own function when an event happens. This is how a page becomes interactive.
The on() method
The method .on() is the best way to attach an event. The first argument is the event name and the second is the function (the handler).
<button id="btn">Click me</button>
<p id="count">0</p>
var n = 0;
$('#btn').on('click', function () {
n++;
$('#count').text(n);
});
$('#btn').trigger('click');
$('#btn').trigger('click');
$('#btn').trigger('click');
console.log($('#count').text());
3
We used trigger() to make the clicks by code. A real user clicks with the mouse.
Shortcut methods
For the common events there are short methods, like .click(), .dblclick(), .hover(), .keyup() and .submit(). They are shorter, but .on() works for all events, also for delegated events, so many developers use only .on().
$('#btn').click(function () { /* same as on('click') */ });
$('#btn').on('click', function () { /* preferred */ });
Common events
| Group | Events |
|---|---|
| Mouse | click, dblclick, mouseenter, mouseleave, mousedown, mouseup, mousemove |
| Keyboard | keydown, keyup, keypress (old) |
| Form | submit, change, focus, blur, input |
| Document and window | ready, load, resize, scroll |
The event object
Your function gets an event object with useful information.
<a id="link" href="https://example.com" class="nav">Go</a>
$('#link').on('click', function (e) {
e.preventDefault(); // stop the browser from opening the link
console.log(e.type); // event name
console.log(e.target.id); // the element which was clicked
console.log($(this).attr('href')); // this is the clicked element
});
$('#link').trigger('click');
click
link
https://example.com
e.preventDefault()stops the default action, like opening a link or sending a form.e.stopPropagation()stops the event from going to the parent elements.thisis the DOM element of the handler.$(this)makes it a jQuery object.
Multiple events and many handlers
<input id="name" type="text">
<p id="info"></p>
$('#name').on('focus blur', function (e) {
$('#info').text('Last event: ' + e.type);
});
$('#name').trigger('focus');
console.log($('#info').text());
Last event: focus
Remove an event with off()
<button id="btn">Click</button>
var clicks = 0;
function add() { clicks++; }
$('#btn').on('click', add);
$('#btn').trigger('click');
$('#btn').off('click', add);
$('#btn').trigger('click');
console.log(clicks);
1
Run only once with one()
<button id="btn">Click</button>
var clicks = 0;
$('#btn').one('click', function () { clicks++; });
$('#btn').trigger('click');
$('#btn').trigger('click');
console.log(clicks);
1
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |