How to Bind jQuery Events to Dynamically Created Elements

Discussion in 'JavaScript and AJAX' started by shabbir, Dec 14, 2013.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    There are multiple ways to attach an event handler in jQuery but all of them does not function exactly the same way. If there are elements created after DOM is loaded, then not all the events associated with them would be triggered if you have not attached the event handlers correctly.

    Example



    Let us say that we have a textarea element in an HTML document.

    HTML:
    <textarea id="MessageArea1" name="MessageArea1" rows="10" cols="40">Added in HTML as MessageArea1</textarea>
    To bind a click event handler to all the textarea's in the document, ideally we would write the following jQuery code
    Code:
    $("textarea").click(function(){
    	// Do something when textarea is clicked
    });
    
    The above code works fine for all those text area that are loaded till now in the document but not those that are added after the above code is executed. So if we want to handle the click event handlers for those textarea as well then we just make sure the above code is executed after all the textarea's are loaded and we normally do that in the ready event.

    Something like this
    Code:
    $(document).ready(function() {
    	$("textarea").click(function(){
    		// Do something when textarea is clicked
    	});
    });
    
    What if we want to be adding adding new textarea's based on some Ajax. How will a click attach the same functionality of click event for them as well?

    The solution is to be using the .on function to attach events handler for all elements now and in the future. Prior to jQuery 1.7, the .live() method was used but is now deprecated and so I will share the sample with the on function only.
    Code:
    $(document).ready(function() {
    	$(document).on("click","textarea",function(){ 
    		// Do something when textarea is clicked
    	});
    });
    
    Here is the HTML to see the issue in action by adding the text area in JavaScript.
    HTML:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
    <head>
    	<title>Binding jQuery Events for Dynamically Created Elements - Go4Expert</title>
    	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <style>
    body{font-family:arial;}
    </style>
    <script>
    $(document).ready(function() {
    	$("textarea").click(function(){
    		$("#output").append("<p>(textarea).click executed on " + $(this).attr("id") + "</p>");
    	});
    	$(document).on("click","textarea",function(){ 
    		$("#output").append("<p>on click executed on " + $(this).attr("id") + "</p>"); 
    	});
    	$("tr").append('<td><textarea id="MessageArea2" name="MessageArea2" rows="10" cols="40">Dynamically Added After Document Loaded as MessageArea2</textarea></td>');
    });
    </script>
    </head>
    <body>
    	<form>
    		<table>
    			<tr><td>
    				<textarea id="MessageArea1" name="MessageArea1" rows="10" cols="40">Added in HTML as MessageArea1</textarea>
    			</td></tr>
    		</table>
    	</form>
    	<div id="output"><h1>Output will be Displayed Here.</h1></div>
    </body>
    </html>
    
    You can find the above code in action here.

    Clicking MessageArea1 will produce the output as
    (textarea).click executed on MessageArea1

    on click executed on MessageArea1
    But Clicking MessageArea2 the output will be

    on click executed on MessageArea2​
     
    ManzZup likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice