Events let you react to what the user does.
Common events
| Method | When |
|---|---|
click() / dblclick() |
clicked / double-clicked |
mouseenter() / mouseleave() |
mouse enters / leaves |
hover(in, out) |
both together |
keyup() / keydown() |
key released / pressed |
focus() / blur() |
field focused / left |
change() |
select, checkbox or input changed |
submit() |
form submitted |
The .on() method (recommended)
$('#btn').on('click', function (e) {
$(this).text('Clicked!');
});
Attach several events: .on('mouseenter mouseleave', fn).
Remove with .off('click').
Event object
e.preventDefault()— stop a link or form's default actione.target— the element that was clickede.which/e.key— which key was pressed
Example
Example — Click, hover and keyup
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<button id="like">👍 Like (0)</button>
<div id="box" style="width:180px;padding:20px;margin:12px 0;background:#eee">Hover over me</div>
<input id="search" placeholder="Type something">
<p>You typed: <strong id="typed"></strong></p>
<a href="https://www.agyanadda.com" id="link">This link is blocked</a>
<script>
$(function () {
let likes = 0;
$('#like').on('click', function () {
likes++;
$(this).text('👍 Like (' + likes + ')');
});
$('#box').hover(
function () { $(this).css('background', '#ffd43b').text('Mouse is in!'); },
function () { $(this).css('background', '#eee').text('Hover over me'); }
);
$('#search').on('keyup', function () {
$('#typed').text($(this).val());
});
$('#link').on('click', function (e) {
e.preventDefault();
alert('Default link action stopped.');
});
});
</script>