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
How to check if event exists on element in jQuery?
To check if event exists on element in jQuery, you need to examine the existing events bound to that element. jQuery provides methods to access the event data stored internally for DOM elements.
Here, I have set a div element −
<div id="demo"> This is demo text. Click here! </div>
When you click the div, an alert is generated. To check if events exist on this element, we use $._data() method to access the internal event data and verify if any events are bound to the element.
$("#demo").click(function() {
alert("Does event exists? - " + hasEvents);
});
The $._data() method retrieves internal jQuery data for an element, including event handlers. We check if the returned events object is not null to determine if events exist.
Example
You can try to run the following code to check if event exists −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#demo").click(function() {
alert("Does event exists? - " + hasEvents);
});
var events = $._data(document.getElementById('demo'), "events");
var hasEvents = (events != null);
// Display the result immediately
$("#result").text("Event exists: " + hasEvents);
});
</script>
</head>
<body>
<div id="demo" style="padding: 10px; background-color: #f0f0f0; cursor: pointer; border: 1px solid #ccc;">
This is demo text. Click here!
</div>
<p id="result" style="margin-top: 10px; font-weight: bold;"></p>
</body>
</html>
In this example, the code checks for events after binding a click handler to the div element. The variable hasEvents will be true since we attached a click event, and this result is displayed both when you click the div and immediately when the page loads.
This method allows you to programmatically determine whether any jQuery events are bound to a specific element, which is useful for conditional event handling and debugging purposes.
