Skip to content Skip to sidebar Skip to footer

Loading Images Into Div Dynamically

I have a list of profile images which appear in a 'menu drop down' div which is initially hidden via CSS. I would like to load these images dynamically (as a list) when each menu i

Solution 1:

Try to use:

$("#divID").html("<img  style='position:absolute' src='path/to/the/ajax_loader.gif'>");

If you using ajax:

functionsendAjax()
    {
        $("#divID").html("<img  style='position:absolute' src='path/to/the/ajax_loader.gif'>");

         // you ajax code

        $("#divID").html(ajaxResponse);
    }

you can also use document.getElementById('divID').innerHTML instead of $("#divID").html(). its also work fine

If you use this method, doesn't need to hide the div using css. its automatically remove after the ajax response.

Solution 2:

Well, you can try this:

<divid="desiredDiv"></div><script>var images = [
    'http://www.example.com/img/image1.png',
    'http://www.example.com/img/image2.png',
    'http://www.example.com/img/image3.png',
    ...
];
for(var i=0; i<images.length; i++) {
    $('#desiredDiv').append('<img src="'+images[i]+'" alt="" />');
}
</script>

Solution 3:

In your HTML leave out the src attribute on each image tag. Instead, add an attribute called data-src and give it the image url.

Then, when the menu is displayed, run the following script:

$('.menu-class img').each(function() {
    $(this).attr('src', $(this).data('src'));
});

Said script requires jquery if you don't already have it

Solution 4:

You can keep the list of images in a JavaScript variable:

var images = [
    'http://www.example.com/img/image1.png','http://www.example.com/img/image2.png','http://www.example.com/img/image3.png',
    ...
];

Then you can load the image whenever you need by creating the image tag:

var i = 0; // the index of the image in the listvar $img = $( '<img>' ).attr({'src':images[i]});

Just append the image to your div and it will be loaded automatically by the browser.

Post a Comment for "Loading Images Into Div Dynamically"