Add Event Handlers to Dynamically Created Elements in jQuery

Add Event Handlers to Dynamically Created Elements in jQuery

In this article, I am going to discuss How to Add Event Handlers to Dynamically Created Elements in jQuery with Examples. Please read our previous article, where we discussed Passing Data to Event Handler in jQuery.

How to add Event Handlers to Dynamically Created Elements?

In the previous articles, we have learned that how to attach the event handler to DOM elements. Now the question arises if that element is not present in our DOM and that is being added by our script. Let us understand this problem by practical example first.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-family: Arial, Helvetica, sans-serif;
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
      p {
        margin: 20px auto;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
        width: 100%;
        padding: 20px;
        border-radius: 30px;
        background-color: rgb(255, 164, 164);
        cursor: pointer;
      }
      button {
        background-color: #1c4450;
        border: none;
        color: white;
        padding: 20px 35px;
        text-align: center;
        text-decoration: none;
        outline: none;
        display: inline-block;
        font-size: 20px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
      }
    </style>
  </head>
  <body>
    <h1>Add Event Handlers to Dynamically Created Elements</h1>
    <div class="container">
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
    </div>
    <button id="btn">Add a new paragraph element</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("p").on("click", function () {
          $(this).fadeOut(500);
        });

        $("#btn").on("click", function () {
          var newParagraph = "<p>New Paragraph</p>";
          $(".container").append(newParagraph);
        });
      });
    </script>
  </body>
</html>

Look at the above example, here, we have already some <p> elements in our DOM. And by clicking the button we are creating new <p> elements. Now run the above code, and you will get the following output,

Add Event Handlers to Dynamically Created Elements in jQuery

Now, click on the Add a new paragraph element button to add new paragraphs as shown in the below image. Here, I have clicked the button two times, so it will add two new paragraphs.

How to Add Event Handlers to Dynamically Created Elements in jQuery with Examples

Now click on the paragraph items.

How to Add Event Handlers to Dynamically Created Elements in jQuery

You can see that when you click on the existing <p> elements they fade out. But when you click on the new <p> elements nothing happens. What is the reason for that?

When the document is ready to execute to the script, we have bound the click event handler to all the <p> element which is present in the DOM but not to those elements which are being added by the script. That’s why they are not fading out. Now, what can we do about that? Let’s see.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-family: Arial, Helvetica, sans-serif;
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
      p {
        margin: 20px auto;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
        width: 100%;
        padding: 20px;
        border-radius: 30px;
        background-color: rgb(255, 164, 164);
        cursor: pointer;
      }
      button {
        background-color: #1c4450;
        border: none;
        color: white;
        padding: 20px 35px;
        text-align: center;
        text-decoration: none;
        outline: none;
        display: inline-block;
        font-size: 20px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
      }
    </style>
  </head>
  <body>
    <h1>Add Event Handlers to Dynamically Created Elements</h1>
    <div class="container">
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
    </div>
    <button id="btn">Add a new paragraph element</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("p").on("click", function () {
          $(this).fadeOut(500);
        });

        $("#btn").on("click", function () {
          var newParagraph = $("<p>New Paragraph</p>").on("click", function () {
            $(this).fadeOut(500);
          });

          $(".container").append(newParagraph);
        });
      });
    </script>
  </body>
</html>

Here we are wrapping the new paragraphs. Run the above code and click on the Add a new paragraph element button to add new paragraphs as shown in the below image.

Add Event Handlers to Dynamically Created Elements in jQuery

Now click on the paragraphs and you will see that existing, as well as new paragraphs, are fade out as shown in the below image.

Add Event Handlers to Dynamically Created Elements in jQuery with Examples

Now you can see that existing, as well as new <p> elements, are fading out. Our problem is solved. But there is a problem. The problem with this approach is that we are binding a click event handler to every <p> item. This means if you have 500 <p> items, then there will be 500 event handlers in the memory and this may negatively affect the performance of your application.

A better way of doing the same from a performance standpoint is shown below. In this example, the click event handler is attached to the parent element (div). Even if you have 500 <p> items, there is only one click event handler in memory.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-family: Arial, Helvetica, sans-serif;
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
      p {
        margin: 20px auto;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
        width: 100%;
        padding: 20px;
        border-radius: 30px;
        background-color: rgb(255, 164, 164);
        cursor: pointer;
      }
      button {
        background-color: #1c4450;
        border: none;
        color: white;
        padding: 20px 35px;
        text-align: center;
        text-decoration: none;
        outline: none;
        display: inline-block;
        font-size: 20px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
      }
    </style>
  </head>
  <body>
    <h1>Add Event Handlers to Dynamically Created Elements</h1>
    <div class="container">
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
      <p>This is a dummy paragraph</p>
    </div>
    <button id="btn">Add a new paragraph element</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $(".container").on("click", "p", function () {
          $(this).fadeOut(500);
        });

        $("#btn").on("click", function () {
          $(".container").append("<p>New Paragraph</p>");
        });
      });
    </script>
  </body>
</html>

The above example will give you the same output as the previous example.

How does this work?
  1. When you click on a <p>, the event gets bubbled up to its parent (div.container) as the <p> does not have an event handler 
  2. The bubbled event is handled by the parent element, as it has a click event handler.
  3. When a new <p> is added dynamically, you don’t have to add the click event handler to it. Since the newly created <p> is added to the same parent element (div.container), the click event of this <p> also gets bubbled up to the same parent and will be handled by it.

In the next article, I am going to discuss jQuery Event Delegation and Undelegation with Examples. Here, in this article, I try to explain How to Add Event Handlers to Dynamically Created Elements in jQuery with Examples and I hope you enjoy this Add Event handler to Dynamically Created Elements in the jQuery article.

Leave a Reply

Your email address will not be published.