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

React Rally 2016 Recap

I recently attended the React Rally conference in Salt Lake City, UT. The conference was about the front end server and client framework React, created by Facebook. Speakers covered topics such as Redux, Relay, RethinkDB, Async and of... Continue →