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 detect eventType in jQuery?
To detect the eventType in jQuery, use the event.type property. This property returns a string representing the type of event that was triggered, such as "click", "mouseover", "keydown", etc. This is particularly useful when you have multiple event handlers bound to the same element or when you want to perform different actions based on the event type.
Example
You can try to run the following code to learn how to detect eventType in jQuery ?
<!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("mouseover mouseout", function(event){
$("div#result").html("Event Type: " + event.type);
});
});
</script>
</head>
<body>
<p>This has mouseover and mouseout event defined. Keep your cursor to see the event type below.</p>
<div id="result">
Move your mouse over the paragraph above to see the event type here.
</div>
</body>
</html>
The output will display different event types based on your mouse interaction ?
When mouse enters the paragraph: Event Type: mouseover When mouse leaves the paragraph: Event Type: mouseout
Multiple Event Types
The event.type property is especially useful when handling multiple events with a single handler function ?
$("button").on("click dblclick", function(event){
if(event.type === "click") {
console.log("Single click detected");
} else if(event.type === "dblclick") {
console.log("Double click detected");
}
});
Conclusion
The event.type property in jQuery provides an easy way to identify which specific event was triggered, making it possible to handle multiple events efficiently with a single handler function.
