jQuery : Adding Event Listeners to HTML elements even before they are rendered

Intro

This article will help you setup event listeners for dynamic elements on the webpage using JQuery.

Pre-requisites

Basic knowledge of JQuery Selectors, Basic event handling in Javascript

Lets Start

  • Create a basic html with our jQuery dependency
<html>
  <head>
    <!-- add jquery dependency -->
    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js"></script>
  </head>
  <body>
    <div class="main">
      <!-- button will appear here -->
    </div>
    <script>
      let buttonHtml = `<button class="btn">Click to turn me RED</button>`
      // add a button 1 second after document is loaded
      $(document).ready(function () {
        setTimeout(() => {
          $(".main").append(buttonHtml);
        }, 1000)
      })


    </script>
  </body>
</html>

This code just adds a button with class btn inside our main div.

Wrong Approach

  • Let's start with what I was doing wrong earlier.
  • Adding more lines to our script that should add a click listener to my button
// on click of our selector, turn our button RED
$(".btn").on('click', function(){
  $(this).css('background','red');
})

Well, See in action

Correct Approach

  • I checked for jQuery documentation and found that there is also an event-delegation approach

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time.

So, all I had to do was add another parameter to our method and change the selector.

So Basically,

Tell our browser, that whenever there is a click event on our .main class element, check if it was made on the .btn specifically.

So I replaced my previous code with this.

$('.main').on('click','.btn', function(){
  $(this).css('background','red');
})

That was it. Boom!

Thank you note.

Thanks for reading. Like and follow for more such articles.
Happy to engage in healthy discussion in comments.

30