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!!!! <cfloop query="gallery"> gallery.add( new Image('#thumb#','#large#','#caption#') ); </cfloop>
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:
<cfloop query="gallery"> <!--- This should probably be done unobtrusively, but it's just so darn convenient! ---> <a onclick="gallery.show(#gallery.currentRow - 1#); return false;" href="##"> <img src="#thumb#" alt="" /> </a> </cfloop>
As always, this solution is far from perfect, and I'd love feedback!
Tags: javascript, tools