Search code examples
jquerychainingdom-manipulation

jQuery access DOM that's just been added


I am adding an image using jQuery to another DOM-element. Now i wan't to fadeout that image that was added, but it's not going very well, i guess because the image was added after the document was loaded!?

Here is my code

$('#t' + u).html('<img style="top: 100px;" src="'+data[dataRnd].img+'"/>').find('img').fadeOut(5000);

Solution

  • Instead of using html(), create the img as a jQuery DOM Object first. After that you can append it to the container and fade it out.

    var $img = $('<img style="top: 100px;" src="'+data[dataRnd].img+'"/>');
    var $container = $('#t' + u).empty();
    
    $img.appendTo($container).fadeOut(5000);
    

    Problems will arise because the animation might start before the image is loaded. As @adaneo correctly suggested, the .load() method can be used to add an event handler on the image when it is loaded and let that start the animation. This still has some cross-browser issues (see Caveats), but you can start the animation in a few seconds in case the load event did not fire.

    $img.on('load', function () {
        $(this).fadeOut(5000);
    }).appendTo($container);
    
    setTimeout(function () {
        $img.trigger('load');
    }, 2000);
    

    jsFiddle Demo