Dynamically Load Images: jQuery Looping

Video tutorial to demonstrate loading of images dynamically using jQuery looping method: .each()

In this tutorial, we take 5 div elements in our html document, and then using each() method, we loop through each of these div tags and insert images in each one of them.

HTML code
index.html


Dynamically load images: jQuery Looping





1
2
3
4
5

Here we have 5 div tags, and we have applied some cascading stylesheet property to it.

jQuery code
my_script.js

$(document).ready( function() {
 
 $("div").each( function(i) {
  $(this).append(""); 
 });
 
});

Here we select all the div tags and loop through each one of them using each() method.
Using this selector, we append image tag with a image to each div present in our html document.

+ is concatenation operator.
i++ is a shorthand notation of i = i + 1;

++i is pre increment.
i++ is post increment.

Similarly,
– -i is pre decrement.
i- – is post decrement.

Ex:

let i = 1;

display or echo ++1; results in 2. after display i = 2;
display or echo i++; results in 1. after display i = 2;

Note: We have our images inside a folder called images.

Video Tutorial: Dynamically Load Images: jQuery Looping



YouTube Link: https://www.youtube.com/watch?v=r-7ljuuljgY [Watch the Video In Full Screen.]



each() method is often used in all the application level programming logic.
We would also use a static method $.each() when we encounter ajax in jQuery. We would explain it in further videos. Stay subscribed to our blog and youtube channel and please like and share our tutorials with your friends.

View Comments

  • Hello This script now randomises an image starting with number 0.png which is located in the img folder.. you can obviously control the amount of images by writing a div tag for each image needed.. a nice way to do this would be by some other loop method rather than writing in this case lots of empty divs so this code can be improved for readability reasons.

    $(document).ready (function(){
    (function($) {
    $.fn.shuffle = function() {
    var m = this.length, t, v;

    while (m) {
    v = Math.floor(Math.random() * m--);

    t = this[m];
    this[m] = this[v];
    this[v] = t;
    }

    return this;
    };
    }(jQuery));

    jQuery(function($) {
    $('div').shuffle().each(function(i) {

    $(this).append(" ");

    });

    });
    });