Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to trigger the same function with jQuery multiple events?
To trigger the same function with multiple events, use the jQuery on() method with multiple events such as click, dblclick, mouseenter, mouseleave, hover, etc.
The on() method provides a flexible way to attach event handlers to elements. You can bind multiple events to the same element using an object notation where each property represents an event type and its corresponding handler function.
Example
You can try to run the following code to learn how to work the same function with jQuery multiple events ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").on({
mouseenter: function(){
$(this).css("background-color", "gray");
},
mouseleave: function(){
$(this).css("background-color", "red");
},
dblclick: function(){
$(this).css("background-color", "yellow");
}
});
});
</script>
</head>
<body>
<p>Click, double click and move the mouse pointer.</p>
</body>
</html>
In this example, the paragraph element responds to three different events ?
- mouseenter ? Changes background to gray when mouse enters
- mouseleave ? Changes background to red when mouse leaves
- dblclick ? Changes background to yellow when double-clicked
Alternative Syntax
You can also use space-separated event names to trigger the same function for multiple events ?
$("p").on("mouseenter mouseleave", function(){
$(this).toggleClass("highlight");
});
Conclusion
The jQuery on() method provides an efficient way to handle multiple events on the same element, either by using object notation for different handlers or space-separated event names for the same handler function.
