March 3, 2013

How to deal with content that will be added later in jQuery?

Question by Develop Smith

I want to control a canvas that is automatically created in the run-time.
The problem here is that jQuery function will have to deal with a content that isn’t exist when the page is ready.

$(document).ready(function(ee) {
     $("#containerInsertBtn").click(function(e) {
         e.preventDefault();
         $("#container").html("<canvas width='300' height='300' id='tk'>fall</canvas>");    
    });

    $("#tk").click(function(eg) {
        alert('tic');
    });

});

The HTML Markup:

<div id="container" contenteditable="true"></div>
<button id="containerInsertBtn">Add Canvas</button>

Answer by Starx

Your code does not work because a dynamically created element will not be included on DOM while the event handler is executed.

Your solution is event delegation. jQuery has .on() to do that.

$("body").on('click', '#tk', function(e) {
    //....
});

You need to specify a parent container to delegate the events to its child elements liek #tk

If you want to delegate to a element based on its tag name, its as same as the above.

$("body").on('click', 'canvas', function(e) {
    console.log($(this)); // you can access the active element by using $(this)
    //....
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!