In keeping with my current “blog-more-about-less” stratagem I thought I’d post a little JavaScript utility I wrote. The idea was just to add “next” and “previous” buttons to an existing gallery, but I thought I’d have a little fun with it, as it may come in handy in the future.
The idea was to create a simple slider object that would keep track of the users position in an array of items. I could cycle through the items, backwards and forwards and fire of item methods. For the gallery I only had to worry about a few basic properties and methods, but I wanted to design this in such a way that adding properties and functionality to my objects would be a breeze.
PS: Current the slider object expects your items contain the methods “update” and “show”. I *know* this is bad, but I’ve had a hard time coming up with a solution that I liked better.
PPS: The example code I’m posting below was done using Prototype and ColdFusion, neither of which are required but are there because I thought it made it easier to get the point across.
Alright, enough gibber jabber.
Image Object:
function Image(thumb,large,caption) {
this.thumb = thumb;
this.large = large;
this.caption = caption;
this.show = function() {
showPhoto(this.large,this.caption);
}
this.update = function() {
$('largeImg').src = this.large;
$('photoCaption').update(this.caption);
}
}
Create and fill it up!
gallery = new Slider();
// don't forget to escape those special javaScript characters!!!!
gallery.add(
new Image('#thumb#','#large#','#caption#')
);
Attach the “previous” and “next” methods to my links. <3 unobtrusive JavaScript!
Event.observe(
'previous',
'click',
function() {
gallery.previous();
}
);
Event.observe(
'next',
'click',
function() {
gallery.next();
}
);
And finally, on the actual thumbnails on the page:
As always, this solution is far from perfect, and I’d love feedback!