Common Events: Click, Hover, Focus, Blur, etc.
Sure, here's an explanation of some common jQuery events along with examples:
1. click
This event occurs when an element is clicked.
// Example: Alert message on button click
$('#myButton').click(function() {
alert('Button clicked!');
});
2. hover
This event occurs when the mouse pointer enters and leaves an element.
// Example: Change background color on hover
$('#myDiv').hover(function() {
$(this).css('background-color', 'lightblue');
}, function() {
$(this).css('background-color', 'white');
});
3. focus
This event occurs when an element gains focus (e.g., when clicked or tabbed into).
// Example: Highlight input field on focus
$('input[type="text"]').focus(function() {
$(this).css('border-color', 'blue');
});
4. blur
This event occurs when an element loses focus (e.g., when clicked away or tabbed out).
// Example: Validate input on blur
$('input[type="text"]').blur(function() {
if ($(this).val().trim() === '') {
$(this).css('border-color', 'red');
} else {
$(this).css('border-color', 'green');
}
});
5. keyup
This event occurs when a keyboard key is released while the element has focus.
// Example: Live search as user types
$('#searchInput').keyup(function() {
var searchText = $(this).val().toLowerCase();
// Perform search logic here
});
6. submit
This event occurs when a form is submitted.
// Example: Prevent form submission and perform validation
$('#myForm').submit(function(event) {
event.preventDefault(); // Prevent default form submission
// Validate form fields and submit via Ajax
});
These examples demonstrate how you can use jQuery to attach event handlers to various actions on elements in your web page, allowing you to create interactive and responsive user interfaces.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
