[Solved]: jQuery Not Working On Dynamically Added Elements

  John Mwaniki /    Updated on 07 Jul 2024

In this article, we will explore why jQuery events fail to work on dynamically added elements and the solution to overcome this challenge.

Dynamic content refers to elements and their contents added to a web page after it has finished loading. This content is in most cases loaded from a server through AJAX and inserted dynamically into the DOM without refreshing the entire page.

This can also be done by dynamically creating new HTML elements or modifying their contents, and appending them to the page using JavaScript when a user performs a certain action such as button clicks.

Why jQuery Events Fail on Dynamically Added Elements

jQuery's event handlers are bound to elements present in the DOM when the page is loaded. When dynamically adding elements, these newly created elements do not have event handlers attached to them by default.

Therefore, if you try to trigger an event on a dynamically added element directly, it won't work as expected.

Example

$(".mybtn").click(function(){
    // Event handler code here
    alert("I feel clicked");
});

If the element with class "mybtn" was dynamically added to the page. The above code will not have any impact on clicking the element.

Solution to Fix jQuery Events on Dynamically Added Elements

To overcome the challenge of jQuery events not working on dynamically added content, you need to implement event delegation.

Event delegation involves attaching an event handler to a parent element that exists in the DOM when the page loads. This way, the events are handled by the parent element, and you can capture events triggered by its dynamically added child elements.

This is done by using the jQuery on() method with the selector of a parent container element that exists when the page loads.

Syntax

$(parentSelector).on(eventType, childSelector, handler)

Parameters Description

Parameter Description
parentSelector Specifies the selector of a parent container element that exists when the page loads.
eventType Specifies the specific event to be triggered by dynamic elements (eg click, focus, mouseover, etc).
childSelector Specifies the selector for the dynamically added element that will trigger an event.
handler Specifies a function with your event handling logic.

To fix the example code shown above on the page, you will need to change it as below:

$("#parentElement").on("click", ".mybtn", function() {
    alert("I feel clicked");
});

In this example, "parentElement" is the ID of the parent element of the element being clicked. The element name, its ID, or class name can be used as the selector of either the parent or child element. document, "html", or even "body" can be used in place of the parent selector.

Example

$(document).on("click", ".mybtn", function() {
    alert("I feel clicked");
});

That's it!

Now jQuery events not firing on dynamically added elements should not worry anymore.