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

ES7 Async Await in JavaScript

This is a blog post on the async and await functionality coming to JavaScript. It is currently on Stage 3 Draft but is well adopted in tools such as Babel which transpiles the code into Generators (which is actually transpiled again by... Continue →