Flexslider: url-targeting

Sliders... we all hate them. But they remain a frequently requested thingy. Flexslider is still my favorite choice as it comes to slider-plugins. In this article I will explain a useful snippit to 'extend' your sliders functionality. That is: url-targeting.

Url targeting

Sometimes it's useful that you can tell trough the url wich slide of the slider should be active. In the following example, we can append a '#slide2' to the url, and the Flexslider will start at the second slide.

Get the current url

First, you'll need to get the current url. You can use 'document.URL' for that. I prefer this one above 'window.location.href' because you only need to get the url (not set it). It's about 91% faster than window.location.href (jsperf test). The url will be stored in the variable 'loc'.


var initSlider;

initSlider = function() {
    var loc = document.URL;
};

Filter out the slide-number

Now you need to filter out the slide-number in the url you just retrieved. You will remove everything before the last occuring '#', including the '#' itself. You also want to remove the text 'slide'. The resulting number will be stored in the variable 'idx'.


var initSlider;

initSlider = function() {
    var loc = document.URL,
        idx = 1;

    if(loc.lastIndexOf('#') !== -1) {
        idx = loc.substr(loc.lastIndexOf('#') + 1).replace('slide', '');
    }
};

Check if the value is a number

Let's be sure that the retrieved number is an legal number. You do this with the 'isNaN' function (more about isNaN()). In the future this will be replaced by the 'Number.isNaN()' function. But the support for this new function is not quite there yet (more about Number.isNaN()).


var initSlider;

initSlider = function() {
    var loc = document.URL,
        idx = 1;

    if(loc.lastIndexOf('#') !== -1) {
        idx = loc.substr(loc.lastIndexOf('#') + 1).replace('slide', '');
    }
    if (isNaN(idx - 0)) {
        idx = 1;
    }
};

Initialize the slider

Now you need to initialize the Flexslider and tell it at which slide he should start at. Flexslider provides you with the 'startAt' property to set the starting slide. Because the first slide has the value 0, you do -1 of the value we got from the url.


var initSlider;

initSlider = function() {
    var loc = document.URL,
        idx = 1;

    if(loc.lastIndexOf('#') !== -1) {
        idx = loc.substr(loc.lastIndexOf('#') + 1).replace('slide', '');
    }
    if (isNaN(idx - 0)) {
        idx = 1;
    }

    idx -= 1;

    $('#slider').flexslider({
        startAt: idx
    });
};