Simple two line Image Randomiser Script with jQuery
It's a common task adding a random header or banner for each page view. If you are already utilising the jQuery library you can add just two lines or if not you have a few more lines to get the job done.
The above shows an example the script in action. Reload the page and a random image will be loaded.
1. Start with an array of images.
Change the image filenames in the array to the actual filenames. There is no need to add the file path; we’ll do that in a moment.
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
2a. Set a random header background with jQuery and CSS background-image.
The following code assumes your header has an ID of #header and your images directory is just “/images”. Change them if necessary.
$('#header').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
2b. Insert a random banner or picture with jQuery and DOM injection
The following code assumes your container has an ID of #banner and your images directory is just “/images”. Change them if necessary.
$('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#banner');
The Old Non-jQuery Way
jQuery is used all over the place and makes things simpler by utilising pre-written bulletproof functions. Sometimes however you either don’t need an entire library to accomplish one simple task or you want to understand the full process of what is going on. I would still use the jQuery method for a site this was the only javascript on as it is then expandable in the future.
If you are not using jQuery you need a few more lines of code. Essentially we create a new array, pick a random image and finally change the source of the specified element.
<img src="images/image1.jpg" id="banner" alt="Random image" />
Add these lines at the bottom of your html document before the closing </html> tag.
<script type="text/javascript">
var images = new Array('images/image1.jpg', 'images/image2.jpg', 'images/image3.jpg', 'images/image4.jpg', 'images/image5.jpg');
var l = images.length;
var random_no = Math.floor(l*Math.random());
document.getElementById("banner").src = images[random_no];
</script>
This article was posted on 5 February 2010 in Code, jQuery
What you have had to say about all this...
Very interesting tutorial. Thank you for sharing. It’s exactly what I was looking for on a current project with a client. Kudos!
- Bryce Wisekalhow about adding alt attributes to the images?
- James PhillipsThis is great. Thanks!
- MattNice one, simple and does what it needs to, what more could we ask!
- NikThat's the end of this article. I hope you found it useful. If you're enjoyed this article why don't you have a look around the archives, where you can find some more tutorials, tips and general ramblings.
comments