DEV Community

Cover image for jQuery : Adding Event Listeners to HTML elements even before they are rendered
Rohit Gupta
Rohit Gupta

Posted on

1

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>
Enter fullscreen mode Exit fullscreen mode

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');
})

Enter fullscreen mode Exit fullscreen mode

Well, See in action

Wrong Approach GIF

Correct Approach

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

// Taken from https://api.jquery.com/on/

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');
})
Enter fullscreen mode Exit fullscreen mode

That was it. Boom!

Correction GIF

Thank you note.

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay