There and Back Again

jQuery Image Strip

Working for Obu Web i’ve found myself spending less time on code I would say meets the definition of AJAX I put in my book and more time on code that used to be called DHTML. But I guess I’m ok calling it AJAX, at least its pronouncable and building little JavaScript widgets is fun.

Today’s widget is an Image Strip, it has a lot of real uses, but the way I like too use it is for fancy visual effects.

Check out the fancy image viewer below. Make sure to pick an image thats a lot large then the current image (start with 9 or 10).

As you can see, an image strip matched with a bit of animation makes for a very nice looking effect (The images by Josh Gomez don’t hurt either). These sort of tricks are really nice for times when you want to look like your using Flash without actually using it.

The basic idea is you take div give it a height and width set its overflow to hidden and then use it as a viewport. You put an absolute positioned image inside and then move an image left or right (or up and down) to view just 1 cell of the image strip.

So lets take a look at simple and useful example, a color chooser for a shirt in a shopping cart.


So the HTML is pretty simple, we have a div with an image in it, and a dropdown that run a javascript function to move our position on the strip.


The CSS is pretty simple but it sets up everything that is happening. Since overflow is hidden on the .strip container what part of the image strip were showing is just a matter of setting a negative left value on the img.

.strip {
        position: relative;
        overflow: hidden;
        border: solid 1px black;
        height: 100px;
        width: 100px;
}
.strip img {
        position: absolute;
        left: 0px;
        top: 0px;
}

The JavaScript is a small object, it provides 2 methods, currentCell and move. currentCell is used to ignore move requests to the same cell and move is the api you interact with. When you create a new ImageStrip you specify the container, the width of each cell and the animation speed in milliseconds. If the speed is set at 0, we immediatly move which is useful for tasks like color versions. If its a larger number like 800 we get a neat animation effect which was shown in the fancy example at the begining of this article.

function ImageStrip(container,cellWidth,speed) {
	this.container = $(container);
	this.image = this.container.find('img');
	
	this.cellWidth = cellWidth;

	this.speed = speed;
} 

ImageStrip.prototype = {
	move: function(to) {
		var from = this.currentCell();

		if (from == to) {
			return false;
		}

		var newLeft = (this.cellWidth * (to-1) * -1);

		if (this.speed > 0) {
			this.image.animate({left:newLeft},this.speed);
		}
		else {
			this.image.left(newLeft+'px');
		}

		return true;
	},
	currentCell: function() {
		var left = this.image.left();
		if (left == 'auto') {
			left = 0;
		}
		else {
			left = parseInt(left);
		}

		return (left/this.cellWidth);
	}
}

And finishing things up here is the full image.

Were gaining 2 main benefits from using an image strip like this. First we make less requests to the server, and if the images in question is small were saving overall file size since there is less overhead. Most importantly in this example there is no image load flash and wait since all the images are already loaded.

Image Strips are a great trick to add to your AJAX toolbox, let me know when you find a place to use one.

I’d like to thank Josh Gomez for helping me the images used in this article.

Stand-alone example versions of the code on this post are available in this posts examples directory.

Unix Tip

If you got a bunch of photos of the same size you can make the combined image strip using Image Magick’s montage command.

montage -geometry +0+0 -tile 10x1 photo-*.jpg complete.jpg

Breaking down the command, -geometry +0+0 tells montage to use no whitespace between the images, -tile 10x1 says to put all 10 images in a single row. photo-*.jpg is the input files and complete.jpg is the output file.

177 thoughts on “jQuery Image Strip

  1. Alex T.

    Very nice!
    ImageMagick also works on Windows. I’m not shure about the montage command, though.

    BTW: Where does jQuery come in to play?

  2. Joshua Eichorn Post author

    Alex: Yeah, i actually have some slick sprite code around here that I use for Icons. When I finally release the code that uses it I’ll write a sprite specific article.

  3. Joshua Eichorn Post author

    Alex: No clue on ImageMagick on windows, I guess i’ve installed it there before but doing cli stuff on windows always pains me since the shell is so bad.

    jQuery is used for the animation effect and the selector support. You could implement something similar without any library at all if you wanted. I just already had jQuery in place and the animation effect is nice.

  4. Binny V A

    I know that it is not the point of this article, but the t-shirt example bugs me. Won’t it be better if you show a image with the t-shirt section transparent and change the background of the cell? That way the background will become the color of the t-shirt.

  5. seventoes

    Great job! Just one suggestion: Use some more of jQuery’s features to get rid of inline script.

    You can get rid of the ugly inline stuff by doing this:
    Remove the onchange=”shirtStrip.move(this.value)” from the select box
    Add an id to the select box, say, id=”shirtStrip”

    Add this to your script:
    $(function() { // Fires on document ready, to be sure all required elements are loaded
    $(“#shirtStrip”).bind(‘change’,function() { // Binds a function to the ‘change’ event of #shirtStrip
    shirtStrip.move(this.value); // Does what it says 😛
    }
    }

    Untested, but i see no reason why it wouldnt work.

  6. Joshua Eichorn Post author

    Binny: That might work in this super simple case, but t-shirts aren’t normally primary colors, they have textures logos.

    Seventoes: That would work, of course it does show off the one downside of a fully unobtrusive approach. It requires more id’s on your document and requires more code. That being said it does look nicer.

  7. Nate

    Do you know where to find an image upload routine that uses jquery and php to show a thumbnail of images as they are uploaded?

  8. Joshua Eichorn Post author

    nate: I haven’t seen anything along the lines of what your thinking, though I don’t think it would be that hard to get the basics up and running.

  9. Josh Gomez

    Seems like it would be trivial to make the strip slide divs through the viewport,
    but I was wondering how to make the strip like a carousel so it loops from the last sprite, back to the first onNext… This would be sweet, and I would definitely steal your code

  10. Joshua Eichorn Post author

    Josh:
    Yeah actually you can slide through anything its just a matter of changing whats in the strip div

    Making it loop back around is just a matter of detecting the end of the strip in move and then setting the left. Though if your using arrows the direction your moving things in could get a little screwy.

  11. Peter Goodman

    There is a bug in the “fancy image viewer”. If you go to image 10, then go straight back to image 1, image 1 will be incrementally too far left.

  12. Robert van Gent

    Hi,

    I’m trying to figure out how to make the hyperlinks actually on top of the imagestrip itsself, so that you can have lets say 8 thumbnails in a strip and showing only 4 of them, then if you click on the most right one everything moves one up to the left.
    Have you seen an example of this ?

    Regards,
    Robert

  13. steve

    yeah, it would be better if it could stitch divs together instead of forcing you to do image assembly. nice enough, but not something I could/would use in its present form.

  14. Pingback: links for 2007-09-04 « Mandarine

  15. Pingback: 240 plugins jquery : sastgroup.com

  16. Pingback: chinatian › jQuery插件超级多

  17. Pingback: CodeRobots ’s Blog » Blog Archive » 240多个jQuery插件

  18. Pingback: links for 2007-12-26 « PaxoBlog

  19. Pingback: Enjoy what you have! » Blog Archive » 强烈推荐:240多个jQuery插件

  20. Pingback: Diversos Links para desenvoledores de javascript | Blog do teo

  21. Pingback: Jquery的N个插件 » NeiLyi.cn [尼尔.易] - PHP,Jquery,代码,点滴

  22. Pingback: Webmaster 38 » Blog Archive » jQuery Image Stip at ajax scripts compound

  23. Pingback: 幽谷寒泉的BLOG » 强烈推荐:240多个jQuery插件

  24. Pingback: 风筝博客

  25. Pingback: LongWay's Blog » Blog Archive 精彩的jQuery插件

  26. Pingback: Ressources pour le développement web et WordPress » i-noova*

  27. Pingback: Grom’s home » Blog Archive » [转]240多个jQuery插件

  28. Pingback: 百变贝贝 » 上百个让你事半功倍的jquery插件

  29. Pingback: 240 adet jquery ekelntisi - Volkan Şentürk

  30. Pingback: » 1000 ressources pour le développement web et WordPress : la grosse grosse liste « css4design : des css pour votre design html

  31. Pingback: jQuery插件集合.(240) | Sapling soliloquize

  32. Pingback: 强烈推荐:240多个jQuery插件 - 胡言乱语

  33. Pingback: 240 plugins jquery | Computer and Technoloy News

  34. Pingback: 经典240多个jQuery插件 | 喜羊羊与懒羊羊的窝

  35. Pingback: Blox.Svbasi · 100+ Scripts pour JQuery

  36. Pingback: Hidden Pixels - JQuery Examples

  37. Pingback: jQueryTips » รวมฮิต jQuery Plugins มากกว่า 200 รายการ

  38. Pingback: Query: Пара сотен плагинов в одной заметке :: Don’t be bad

  39. Pingback: “The Complete Guide” for jQuery Developer- Reblog « Dynamic Disruption

  40. Pingback: 240 Plugin List in jQuery | Marius Dima

  41. Pingback: 200+ jQuery插件 | 浮世失焦

  42. Pingback: 多个jquery效果演示效果示例 - 虾米碗糕|十里地后院

  43. Pingback: Simone D’Amico » Blog Archive » [jQuery] 240 plugins per jQuery

  44. Pingback: imagic’s blog » Blog Archive » JQUERY插件集合

  45. Pingback: jQuery Eklentileri | Bir Öğrenci Klasiği

  46. Pingback: srui’s blog » 240多个jQuery插件

  47. Pingback: 强烈推荐:240多个jQuery插件 | 好好学习