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

ES6 Lambda Expressions

This is the part of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements. In this blog we focus on the lambda expressions, also called arrow functions, introduced in ES6.... Continue →