Lesson 6: More jQuery Events
Dive deeper into jQuery event handling with advanced mouse, form, and window interactions - master event delegation and best practices.
Advanced Mouse Events
jQuery provides granular control over mouse interactions beyond simple clicks and hovers.
mousedowntriggers when any mouse button is pressedmouseuptriggers when a mouse button is releasedmousemovetracks mouse movement over elementsmouseenterandmouseleaveprovide precise hover control- Events include position and button information
Press and Release Demo
Press and release mouse buttons on the box below to see the events:
Press any mouse button here
$("#pressBox").mousedown(function(e) {
const button = getButtonName(e.which);
$("#pressStatus").text(`Mouse DOWN: ${button} button`).show();
$("#pressureBar").css("width", "100%");
});
$("#pressBox").mouseup(function(e) {
const button = getButtonName(e.which);
$("#pressStatus").text(`Mouse UP: ${button} button released`).show();
$("#pressureBar").css("width", "0%");
});
function getButtonName(buttonId) {
switch(buttonId) {
case 1: return "Left";
case 2: return "Middle";
case 3: return "Right";
default: return "Unknown";
}
}
Mouse Position Tracking
Move your mouse in the area below to track position and events:
$("#mouseTracker").mousemove(function(e) {
const offset = $(this).offset();
const x = e.pageX - offset.left;
const y = e.pageY - offset.top;
$("#mousePointer").css({
left: e.pageX,
top: e.pageY
});
$("#eventInfo").text(`X: ${x}px, Y: ${y}px`);
});
$("#mouseTracker").mouseenter(function() {
$(this).css("background-color", "#e3f2fd");
});
$("#mouseTracker").mouseleave(function() {
$(this).css("background-color", "#f0f0f0");
});
Advanced Form Events
jQuery provides precise control over form interactions beyond basic focus and blur.
Focus and Blur Events
Interact with the form fields to see focus and blur events:
$(".yinfo").focus(function() {
$(this).css("background-color", "#e3f2fd");
$("#focusBlurStatus").text(`Field focused: ${$(this).attr('placeholder')}`).show();
});
$(".yinfo").blur(function() {
$(this).css("background-color", "white");
$("#focusBlurStatus").text(`Field blurred: ${$(this).attr('placeholder')}`).show().delay(1500).fadeOut();
});
Form Validation Events
Try submitting the form with valid/invalid data:
$("#validateBtn").click(function(e) {
e.preventDefault();
const username = $("#username").val();
const email = $("#email").val();
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(username.length < 4) {
$("#validationStatus").html(" Username must be at least 4 characters").css("color", "var(--error)").show();
$("#username").css("border-color", "var(--error)");
} else if(!emailRegex.test(email)) {
$("#validationStatus").html(" Please enter a valid email").css("color", "var(--error)").show();
$("#email").css("border-color", "var(--error)");
} else {
$("#validationStatus").html(" Form is valid!").css("color", "var(--success)").show();
$("input").css("border-color", "var(--success)");
}
});
Window and Document Events
Respond to browser window changes and document interactions.
Scroll Depth Tracking
Scroll in this container to see your scroll position:
Scroll position: 0px
Scroll percentage: 0%
Bottom of content area
$(".demo-target").scroll(function() {
const scrollPos = $(this).scrollTop();
const maxScroll = $(this)[0].scrollHeight - $(this).innerHeight();
const scrollPercent = Math.round((scrollPos / maxScroll) * 100);
$("#scrollDepth").text(scrollPos);
$("#scrollPercent").text(scrollPercent);
});
Event Delegation Techniques
Event delegation allows you to handle events for dynamic content efficiently.
Basic Delegation
Handle events for current and future elements:
$("#container").on("click", ".item", function() {
console.log("Item clicked:", $(this).text());
});
Multiple Events
Handle multiple events with one handler:
$("#container").on(
"mouseenter mouseleave",
".item",
function(e) {
$(this).toggleClass("highlight");
}
);
Data Passing
Pass data to event handlers:
$("#container").on("click", {
info: "Custom data"
}, function(e) {
console.log(e.data.info);
});
Namespaced Events
Organize events with namespaces:
// Add namespaced event
$("#element").on("click.custom", handler);
// Remove only namespaced events
$("#element").off(".custom");
Dynamic List with Delegation
Add items to the list and click them:
- Item 1 (click me)
- Item 2 (click me)
// Event delegation for dynamic items
$("#dynamicList").on("click", "li", function() {
$(this).toggleClass("highlight");
$("#listStatus").text(`Clicked: ${$(this).text()}`).show().delay(1500).fadeOut();
});
// Add new items
$("#addItemBtn").click(function() {
const count = $("#dynamicList li").length + 1;
$("#dynamicList").append(`