Common events: click, hover, focus, blur, etc
Sure, here's an explanation of some common jQuery events along with examples:
-
click: This event occurs when an element is clicked.
// Example: Alert message on button click $('#myButton').click(function() { alert('Button clicked!'); });
-
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'); });
-
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'); });
-
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'); } });
-
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 });
-
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.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.