March 14, 2012

jQuery AJAX – Creating DOM elements

Question by Kolind

I am having this function in jQuery where I’m getting new posts with AJAX and PHP. And then creating a new div and appending the post to it.

Here is my code:

function getMorePosts(latestPost){

    $.ajax({
        type: "POST",
        url: "/includes/classes/handler.php?do=getMorePosts",
        data: "&latestPost="+latestPost,
        cache: false,
        success: function(data){
            if(data){
                $('#addUpdate textarea').val('');
                $('<div id="newPosts"></div>').insertAfter('.myDeskAdd');
                $(data).prependTo('#newPosts');
            }
        }
    });
    return false;
}

Now, data is all of HTML code from my handler.php. Everything works, it’s appending and I can see the result on the screen. And it’s correct – nice!

But here is my problem:
When it’s added to the screen, it’s like I cant ‘use’ the DOM elements. For example: I have an image which I can click, and then it has to call an alert from jQuery, but it’s not. And all other jQuery effects bound to the dom elements created doesn’t work.

Those elements not working DOES work if I press F5.

I have tried html(), prepend(), append() and so on.

Answer by Shyju

for all dynamic content (loaded from ajax), bind methods using jQuery on. Then it should work

instead of this,

 $(".imageClass").click(function(){
    alert($(this).html());    
 });

Use this

 $(".yourContainerDiv").on("click", ".imageClass", function(event){
     alert($(this).html());    
 });

http://api.jquery.com/on/

Answer by Starx

When elements are dynamically generated, they will not attach to previous event handlers.

You have to use .on() method to delegate the event handlers.

Example:

$(".yourmajoreventhandler").on('click', function() {
    //do your stuff
});

Delegation Example:

$("body").on('click', ".yourmajoreventhandler", function() {
    //do your stuff
});

Now, every time, you generate a element with class yourmajoreventhandler the above function will run.

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!