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 @ 5:12 pm by Ian Tearle
If you would like to discuss anything about this post, please be polite and add your comments below.
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".
If you would like to discuss anything about your next project please drop me a line.
Projects start at £99.00 per month
We normally book 2–3 months in advance.
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!