iantearle.com

jQuery Random Image Selector

Just a very short, and perhaps simple demonstration of how to randomly display a background image from a CSS sprite using only jQuery and CSS background positions. Great if you have a changing banner on your website.

Firstly I will make this into a plugin with only one variable you will need to change depending on the amount of images in your sprite, this is in the var $imageNumber.

 $.fn.randomImage = function (){ var $imageNumber = 8,  // Set the amount of images in the Sprite $height = $('> div', this).innerHeight(), $random_num = Math.random() * $imageNumber - 1, $multiple = Math.round($random_num), $random = $height * $multiple jQuery('.image').css(  {'background-position' : '0px -' + $random + 'px',  'display' : 'block' }  )}; 

The only necessities you will need in your html is a div with a class of image inside your selectable div, which you select with the following:

jQuery('#image-container').randomImage();

Your CSS will have to define the height of the div.image which in turn should equal the height of the individual image in your sprite.

Posted On: Tuesday, August 25th, 2009 @ 6:12 pm by Ian Tearle


0 Comments

There are no comments on this entry. You should add one below.

Leave a comment

Be kind

If you would like to discuss anything about this post, please be polite and add your comments below.


 
 

Additionally

No HTML is allowed. All links, and new lines will be automagically converted to HTML for you.
Notice to spammers, all links will be sanitized with rel="nofollow".


Contact Me

Get In Touch

If you would like to discuss anything about your next project please drop me a line.


 

Prices

Startup Websites: £19.00 per month
Commerse Websites: £39.00 per month
Native Apps: £2000

Additionally

No matter how small your project is, or if the prices above scare you, please do get in touch, I shall always listen and will advise freely alternative ideas or solutions. If you are a charity, let's talk!


Find Me On