In one recent project I had to incorporate a traditional slider on the front page of a WordPress installation to showcase the range of products this site was selling. I was a little lazy and bought a popular package to accommodate the needs of my clients’ request.
Unfortunately though, after tinkering around with it, I found it more of a nuisance than a help. Even after setting the package to use no styling it was still difficult to manipulate the object’s css properties to do what I wanted.
In the end I thought to myself, Why don’t I just roll my own?
My requirements weren’t that complicated.
All I needed was something that could do the following:
- Randomly loop through a set of images (and then keep that rotation)
-
FadeIn
andFadeOut
of the images (the client didn’t need anything fancy) -
Images that are confined to the width and height of the
div
element (if the image is too small, stretch it, if it’s too big shrink it)
I found by using the
background
CSS properties on a div element perfect for my needs. Here’s the resulting output:
The only HTML needed:
<div class="my-bg-slider"></div>
The CSS on this object needed:
.my-bg-slider {
background: url("/wp-content/uploads/2012/10/DSC_011.png") no-repeat;
width: 960px;
height: 640px;
background-position: top left;
background-size: 100%;
}
Obviously the URL of the image, the width and height properties can all be changed to suit your needs.
The JavaScript
Placed above the
</body>
tag:
Conclusion
As you can see it’s a relatively simple jQuery slider that uses Underscore.js to help with the array utilities.
Have a play around with it and let me know how you go. Of course, there are several ways to extend this by having an array of objects instead of an array of strings and then using the settings of the object to change the type of effect, adding content on the slide (etc).
You never know maybe the client will want extended functionality on the home page slider! At the moment, it meets the intended purpose.