jQuery Event Handling Guide
jQuery provides six categories of basic events:
- Page events
- Mouse events
- Keyboard events
- Form events
- Edit events
- Scroll events
1. Page Events
In jQuery, $(document).ready() replaces JavaScript's window.onload. While they serve a similar purpose, there are key differences.
1.1 JavaScript's onload Event
In JavaScript, onload executes once the document has fully loaded, including all external resources.
Syntax:
window.onload = function(){
// code
}
Explanation:
The onload event only fires after all DOM elements and all external files (images, external CSS, external JavaScript, etc.) have been completely loaded.
1.2 jQuery's ready Event
In jQuery, the ready event executes once the DOM is ready, without waiting for external resoruces.
Syntax:
$(document).ready(function(){
// code
});
Explanation:
The ready event fires as soon as all DOM elements are loaded, without waiting for images, external CSS, or JavaScript files. This significantly improves page responsiveness and user experience compared to window.onload.
1.3 Four Ways to Write the ready Event
// Method 1:
$(document).ready(function(){
// code
});
// Method 2:
jQuery(document).ready(function(){
// code
});
// Method 3 (most common):
$(function(){
// code
});
// Method 4:
jQuery(function(){
// code
});
Explanation:
- Method 1 selects
documentand calls theready()method. - Method 2 uses the jQuery alias:
$()is equivalent tojQuery(). - Method 3 is the most commonly used shorthand.
1.4 Important Note about ready vs onload
In JavaScript, window.onload can only be assigned once. If assigned multiple times, only the last assignment will execute. In jQuery, multiple ready event handlers can be registered and will all execute.
2. Mouse Events
Common jQuery mouse events include:
click– mouse clickmouseover– mouse enters elementmouseout– mouse leaves elementmousedown– mouse button pressedmouseup– mouse button releasedmousemove– mouse moves within element
2.1 Click Event
You can attach a click event to any element.
2.2 Mouse Enter and Leave
mouseover fires when the mouse enters an element, and mouseout fires when it leaves. These are often used together, for example in dropdown menus where the submenu appears on mouseover and hides on mouseout.
Example with method chaining:
$('#element').mouseover(function(){
// show submenu
}).mouseout(function(){
// hide submenu
});
// Separate calls
$('#element').mouseover(function(){
// show submenu
});
$('#element').mouseout(function(){
// hide submenu
});
Both code blocks achieve the same result. jQuery supports method chaining when performing multiple operations on the same object.
2.3 Mouse Press and Release
mousedown– fires when the mouse button is pressed.mouseup– fires when the mouse button is released.
3. Keyboard Events
keydown– fires when a key is pressed down.keyup– fires when a key is released.
Example: Counting characters as user types
$('#input').keyup(function(){
var length = $(this).val().length;
$('#counter').text(length);
});
Explanation:
Every time the user releases a key after typing a character, the keyup event fires. We then calculate the length of the string entered.
Example: Validating input
4. Form Events
focusandblurselectchangesubmit
4.1 Focus and Blur
focus– fires when an element gains focus.blur– fires when an element loses focus.
Only form elements (radio buttons, checkboxes, text inputs, textareas, selects) and hyperlinks can receive focus. You can test this by pressing the Tab key on a page.
Example: Search box placeholder effect
$('#search').focus(function(){
$(this).val('');
});
$('#search').blur(function(){
if($(this).val() === ''){
$(this).val('Search...');
}
});
Analysis: When the text box gains focus (cursor appears), the hint text disappears. When it loses focus and is empty, the hint reappears.
Modern HTML5 provides the placeholder attribute for this effect:
<input type="text" placeholder="Search...">
Example: Auto-focus
$('#myInput').focus();
focus() can be used as both an event and a method.
4.2 Select Event
The select event fires when text inside an <input type="text"> or <textarea> is selected.
$('#myText').select(function(){
console.log('Text selected');
});
Example: Auto-select all text
$('#myInput').focus(function(){
$(this).select();
});
Like focus(), select() can be used as both an event and a method.
4.3 Change Event
The change event is commonly used with form elements that have multiple options:
- Radio buttons: fires when an option is selected.
- Checkboxes: fires when a checkbox is changed.
- Dropdown lists: fires when a new option is selected.
Example: Radio button
$('input[type="radio"]').change(function(){
var value = $(this).val();
$('#result').text('Selected: ' + value);
});
Example: Checkbox select/deselect all
$('#selectAll').change(function(){
$('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
Example: Dropdown menu
$('#mySelect').change(function(){
var url = $(this).val();
window.open(url, '_blank');
});
When a new option is selected, the change event triggers and opens the corresponding page in a new window.
5. Edit Events
The most common edit event in jQuery is contextmenu.
Example: Disable right-click
$(document).contextmenu(function(e){
e.preventDefault();
});
Example: Change background on right-click
$(document).contextmenu(function(e){
e.preventDefault();
$('body').css('background-color', 'yellow');
});
6. Scroll Events
The scroll event fires when the page's scrollbar is moved. Its very useful for "back to top" features and flat design animations.
Syntax:
$(window).scroll(function(){
// code
});
Scroll events are often used together with scrollTop().
Example: Fixed navigation
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
body{height:1800px;}
#box1,#box2 { display:inline-block; width:100px; height:100px; }
#box1 { background-color:Red; }
#box2 { background-color:Orange; }
</style>
<script src="js/jquery-1.12.4.min.js"></script>
<script>
$(function () {
var top = $("#box2").offset().top;
$(window).scroll(function () {
if ($(this).scrollTop() > top) {
$("#box2").css({"position": "fixed", "top": "0"});
} else {
$("#box2").css({"position": "relative"});
}
});
})
</script>
</head>
<body>
<div id="box1"></div><br />
<div id="box2"></div>
</body>
</html>
Explanation:
When the scroll distance exceeds the distance of box2 from the top, box2 becomes fixed at the top. Otherwise, it remains static.
Example: Back to Top button
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
body { height:1800px; }
div {
position:fixed;
right:50px;
bottom:50px;
display:none;
width:40px;
height:40px;
color:white;
background-color:#45B823;
font-family:微软雅黑;
font-size:15px;
font-weight:bold;
text-align:center;
cursor:pointer;
}
</style>
<script src="js/jquery-1.12.4.min.js"></script>
<script>
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 300) {
$("div").css("display", "inline-block");
} else {
$("div").css("display", "none");
}
});
$("div").click(function () {
$("html,body").scrollTop(0);
});
})
</script>
</head>
<body>
<h3>Green leaves, a feeling of first love.</h3>
<div>Back to Top</div>
</body>
</html>
Explanation: When you scroll down more than 300 pixels, the "Back to Top" button appears. Clicking it scrolls the page back to the top, and the button disappears again.