Dynamically adding images with only client side

This is a way to add images to say a carousel when you don’t know much about the number of images or where it is. Completely configurable.

Using the URL query string we can get the configurable options. This is a way to parse it using regex.

function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }

We basically call the function by calling “addImage(1)” with 1 being the start

function addImage(counter) {
            var src = getParameterByName('path') + counter +(getParameterByName('filetype')||'.png');
            var img = new Image();
            img.onload = function() {
                img.className = "slide";
                if (counter == (getParameterByName('start')||1)) {
                    $("#items").append("<div class=\"active item\">"+img.outerHTML+"</div>");
                } else {
                    $("#items").append("<div class=\"item\">"+img.outerHTML+"</div>");
                }
                counter++;
                addImage(counter);
            };
            if (counter-1 !== (getParameterByName('end')||'noend')) {
                img.src = src;
            }
        }

The only inefficiency in the code is that it will fail at one point where the image does not exist. But if we do not have access to server side (as was my case) then we cannot really avoid this.

 
1
Kudos
 
1
Kudos

Now read this

The argument for const

Lately as my team moves towards a mandatory ES6 development cycle, we often go into arguments about which keyword to use to declare a variable. As outlined in my previous blog, ES6 brings 2 new variable declaration keywords to... Continue →