I want to make something similar to an image slider. The same logic that goes into a slider is something I need a lot. I know a million plugins and tutorials exist but what I want is to learn from basic jQuery patterns like the ‘slider’ or ‘accordion’ without any of the fluff. I want to look over very basic jQuery patterns to learn from.
Would one of the patterns found in the JavaScript Pattern Collection be what I am looking for?
There is not enough logic in an image slider to warrant a proper software design pattern.
Having a look at your link, many of these are not patterns but simply descriptions of things you can do in javascript
For the image slider itself let’s look at it in two components:
User interaction component: buttons (prev, next) or slider
Image component: display image currently selected
All you really have to do is store the index of the currently selected image and lookup what x position to slide the image slider to when you select that image.
Here is a rough example:
http://jsfiddle.net/mattdlockyer/bNnEw/
You’ll see that it’s mostly a functional loop in the beginning that’s doing all the leg work and storing the correct indexes to slide the
#imagesdiv to using the animate function in jQuery. This is called when the user interacts with the buttons but just as easily could be called when a slider fires it’s slide event. See here for more info on sliders: http://jqueryui.com/slider/Personally I would take all this functional programming and put it into a proper javascript module. Check out this link for a great example of how to use the module pattern: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Basically the concept of an image slider alone does not warrant a pattern, but the utility of wrapping it up in a module so that it is reusable, perhaps even several times on the same page, is definitely worth doing.
Javascript is a functional language and there are a lot of “patterns” for writing clean, portable, functional code but they don’t equate to OOP design patterns IMHO.
Enjoy the fiddle, hope this helps you in your javascripting adventures.