This website collects cookies to deliver better user experience
jQuery : Adding Event Listeners to HTML elements even before they are rendered
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 --><scriptsrc="https://code.jquery.com/jquery-3.6.0.slim.min.js"></script></head><body><divclass="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