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 bind events on dynamically created elements using jQuery?
When working with dynamically created elements in jQuery, regular event binding methods like click() or on() directly on elements won't work because these elements don't exist in the DOM when the page loads. To solve this, you need to use event delegation by binding events to a parent element that exists at page load.
The key is to use $(document).on(event, selector, handler) or bind to a specific parent container. This way, the event is attached to an existing element and will trigger when the specified selector matches any current or future child elements.
Example
Here's a complete example that demonstrates how to bind events on dynamically created elements. We'll create a list where you can add new items and remove them using event delegation −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
ul { list-style-type: none; padding: 0; }
li { padding: 8px; margin: 4px; background: #f0f0f0; border-radius: 4px; }
.del { color: red; margin-left: 10px; cursor: pointer; font-weight: bold; }
button { padding: 10px 15px; margin: 10px 0; }
</style>
<script>
$(document).ready(function(){
// Add new list items dynamically
$("button").click(function(){
$("ul").append("<li>New item <a href='javascript:void(0);' class='del'>×</a></li>");
});
// Event delegation - bind to document for dynamically created elements
$(document).on("click", "a.del", function() {
$(this).parent().remove();
});
});
</script>
</head>
<body>
<h3>Dynamic Element Event Binding Demo</h3>
<button>Add New Item</button>
<p>Click the button to add new list items. Click the × symbol to remove items.</p>
<ul>
<li>Original item <a href='javascript:void(0);' class='del'>×</a></li>
</ul>
</body>
</html>
In this example, $(document).on("click", "a.del", function()) uses event delegation to handle clicks on delete links, even those added dynamically. The event is bound to the document, but only triggers when the clicked element matches the a.del selector.
This approach ensures that all dynamically created elements with the specified selector will have the event handler attached, making your jQuery applications more robust and maintainable.
