How to bind jQuery events on elements generated through other events?

Use the jQuery on() method to bind jQuery events on elements generated through other events. This method is particularly useful for event delegation, which allows you to attach events to elements that may not exist when the page loads but are created dynamically later through JavaScript or other events.

The on() method works by attaching the event listener to a parent element (often the document) and listening for events that bubble up from child elements matching the specified selector. This ensures that even dynamically created elements will respond to events.

Example

You can try to run the following code to learn how to use the on() method to bind jQuery 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(){
            // Event delegation using on() method
            $(document).on({
                mouseenter: function (e) {
                    alert('Mouse entered: ' + $(this).text());
                },
                mouseleave: function (e) {
                    alert('Mouse left: ' + $(this).text());
                }
            }, '.demo');
            
            // Button to add new elements dynamically
            $('#addElement').click(function(){
                var newDiv = '<div class="demo">New Demo Element</div>';
                $('body').append(newDiv);
            });
        });
    </script>
</head>
<body>
    <h1>Event Delegation Example</h1>
    
    <div class="demo" id="d1">Demo One</div>
    <div class="demo" id="d2">Demo Two</div>
    
    <button id="addElement">Add New Demo Element</button>
    
    <p>Mouse enter and leave on any .demo element will generate alert boxes, even for dynamically added elements.</p>
</body>
</html>

In this example, the $(document).on() method attaches event handlers for mouseenter and mouseleave events to any element with the class .demo. Even when new elements are added dynamically using the "Add New Demo Element" button, they will automatically have the same event handlers attached.

Conclusion

The jQuery on() method with event delegation is essential for binding events to dynamically generated elements, ensuring that all current and future matching elements respond to the specified events.

Updated on: 2026-03-13T19:05:21+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements