2

I have a variable number of sliders on a page. Each slider contains a variable number of slides, and a pair of prev/next buttons to navigate sequentially through its respective slides.

Here is the markup for a typical slider:

<section class="foo">
    <button class="prev"></button>

    <ul class="container slider">
        <li class="slide" id="a01"></li>
        <li class="slide" id="a02"></li>
        <li class="slide" id="a03"></li>
    </ul>

    <button class="next"></button>
</section>

Each slider should know the index of the slide it is currently showing. This leads me to believe that on page load, I should loop through all $('.slider') elements and instantiate an object for each. How do I write the class that defines the slider? It should have a property that contains the index of the current slide being shown, and a method that increments or decrements that property depending on whether the user clicked 'next' or 'prev'. I've come as far as this:

var slider = function () {
    this.pager = 0;
    this.incrementPager = function () {
        console.log(this.pager++);      
    };
};

$(function () {
    $('.prev, .next').click(slider);
});

... But my code doesn't do much :)

4
  • First off, JavaScript doesn't have classes, only prototypes and functions that are callable as constructors (using the new keyword), in which case they return an object. What you refer to as a class is actually a constructor. Secondly, since constructors are just functions like any other function, they can be used as such. Your snippet merely uses the slider reference to a nameless function as a callback for the click event. It's also convention to write your constructors with an UpperCase first char. Lastly: I think closures will serve your purposes better... but that's just me Oct 10, 2012 at 15:43
  • Your code probably works, but this won't point to any old object, it's a reference to the clicked element, to which you're assigning a property (pager) and a method (incrementPager) which is never called. on the latter: even when you use the slider reference as a constructor, you'll end up creating new function objects for each instance. Not ideal, so you really are better of augmenting the prototype. If you don't know what I mean by that, google returned this as first result Oct 10, 2012 at 15:47
  • Thanks Elias, I'm starting to get a better understanding. What's an elegant way to loop through .slider elements and create an object for each of them? Oct 10, 2012 at 15:49
  • Since this is tagged jQuery, you may want to consider building a plugin for this functionality. I've found the following a great resource: addyosmani.com/resources/essentialjsdesignpatterns/book/… Oct 10, 2012 at 16:04

3 Answers 3

4

Here's how to make a jQuery plugin, which I think is a better way since you're using jQuery, which is not really meant for Class based OO.

$.fn.slider = function() {
    $(this).each(function() {
        var wrapper = $(this);
        var index = 0;
        var listItems = wrapper.find('.slide');
        wrapper.find('.prev').click(function(){
            if (index > 0) {
                $(listItems[index]).removeClass('active');
                index--;
                $(listItems[index]).addClass('active');
            }
        });
        wrapper.find('.next').click(function(){
            if (index < listItems.length - 1) {
                $(listItems[index]).removeClass('active');
                index++;
                $(listItems[index]).addClass('active');
            }
        });

    });
};

And you could use it like

$('section').slider();

Working Example http://jsfiddle.net/MR8wE/

If you really want some OO in there you could do the following (but I think it goes against how jQuery works).

/**
 * Adds behavior to the HTML for a slider
 */
function Slider(wrapper) {
    var me = this;
    me.wrapper = $(wrapper);
    me.index = 0;
    me.listItems = wrapper.find('.slide');
    wrapper.find('.prev').click(function(){
        me.prev(); 
    });
    wrapper.find('.next').click(function(){
        me.next();
    });                    
}

Slider.prototype.next = function() {
    this.go(1;)
}
Slider.prototype.previous = function() {
   this.go(-1);
}
Slider.prototype.go = function(steps) {
    var oldIndex = this.index;
    var newIndex =  oldIndex + steps
    if (newIndex >= 0 && newIndex < this.listItems.length ) {
        $(this.listItems[oldIndex]).removeClass('active');
        $(listItems[new]).addClass('active');
        this.index = newIndex;
    }

}

Then you would use it like

var sliders = [];
$('section').each(function(){
     sliders.push(new Slider(this));        
});

// Control the slider without user intervention
sliders[0].next();
sliders[1].go(2);

Example http://jsfiddle.net/MR8wE/2/

1
  • All answers were fantastic, so they're all upvoted. I really dig the plugin approach (even though it isn't what I originally asked for), so I've selected this answer and used your snippet as the basis for my own plugin. Thanks! Oct 11, 2012 at 13:15
2

In response to the question in the comments:

function Slider(elm)
{
    this.domElement = elm;
    this.pager = 0;
}
Slider.prototype.incrementPager = function()
{
    this.pager++;
};//all instances share this method ==> only 1 function object in mem.
$(function()
{
    var objectCollection = (function(elements)
    {
        var toReturn = [];
        var scanElementsFunction = function()
        {//declared in this scope, to have access to elements var
            'use strict';//avoid setting globals
             if (this.allElems === undefined)
             {
                 this.allElems = elements;
             }
             return this.allElems;
        };
        elements.each(function(idx,el)
        {
            toReturn[idx] = new Slider(el);//<-- pass DOMElement to constructor
            toReturn[idx].getAll = scanElementsFunction;//<-- reference, no new function object
        });
        return toReturn;
    }($('.prev, .next')));//this scope preserves the elements returned by jQuery selector
    console.log(objectCollection);
});

There's nothing really useful in there, but I tried to incorporate as much tricks and tips while keeping the snippet as short as possible. If some of the code is unclear, let me know and I'll provide some more explanation (which might take an hour or two, 'cause I'm going to grab a bite now :))

2

The following approach uses the more formal constructor function and prototype which keeps it quite lightweight rather than stacking enclosures. The constructor is...

function Slider(slides, transition) {

    // Keeps a reference to the current slide index
    this._current = 0;

    // An array of slides
    this._slides = slides;

    // A transition function
    this._transition = transition;
}

It accepts an array of slides and a function which will be given two slides when we transition between them. This means we keep control of our transition effect by externalizing it. It is also framework agnostic and has no dependencies to jQuery or any other framework. The constructor itself doesn't do much. The following method is our meat...

// The function that swaps slides
Slider.prototype.goto = function(i) {

    // Do a bit of sense checking
    if(i > this._slides.length || i < 0)
        throw new Error("Slide does not exist");

    // Swap the slides by passing them to the transition function
    var currentSlide = this._slides[this._current];
    var nextSlide = this._slides[i];
    this._transition(currentSlide, nextSlide);

    // Update the current index
    this._current = i;
};

It takes the new index for a slide and passes the old and the new slide to the transition function. It then updates the index it uses for tracking the current slide. We then want to implement a rotating previous and next function so the following methods describe how we can do that using modulus, note we have to add the length of the slides because negative modulus does not work how we want it to for this function.

// Calculate the next index as a rotating index
Slider.prototype.getNextIndex = function() {
    return (this._current + 1) % this._slides.length;
};

// Calculate the previous index as a rotating index
Slider.prototype.getPrevIndex = function() {
    return (this._current + this._slides.length - 1) % this._slides.length;
};

Then we add some sugar...

// Sugar to go next and prev
Slider.prototype.next = function() {
    this.goto(this.getNextIndex());
};
Slider.prototype.prev = function() {
    this.goto(this.getPrevIndex());
};

You may have a problem with associating the prev and next buttons with their sliders. You can find them before and after the slider element or as I have done below have them contained in the slider element. To set up sliders using jQuery you could do the following...

$(".slider").each(function() {
    var slider = new Slider($(this).find(".slide"), function(a, b) {
        $(a).hide();
        $(b).show();
    });
    $(this).data("slider", slider);
    $(this).find(".prev").click(function() {
        slider.prev();
    });
    $(this).find(".next").click(function() {
        slider.next();
    });
});

EDIT Here is it in action http://jsfiddle.net/w8u69/

And because the logic for transitioning is exposed you can quite easily add in transitioning effects without modifying the original Slider "class". http://jsfiddle.net/w8u69/1/

EDIT Just to show the power in this approach, without modifying the original slider "class" you can add in additional logic to automatically move between slides. You can do this with a decorator, or with inheritance, but this example shows how it can be done with composition. http://jsfiddle.net/w8u69/4/

One last thing and this is possibly the most important thing about the pure OO approach, by simply changing the integration code and keeping the OO "classes" untouched, we can reuse the logic we have written for the slider and plug it into a completely different framework. This fiddle shows it working with MooTools http://jsfiddle.net/w8u69/5/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.