eozzy
eozzy

Reputation: 68650

Basic image rotation with jQuery

I'd like to test banner (two css background images) and rotate them randomly on each page reload. Is it possible to achieve something like that without using any plugins?

I just need to rotate two images, which is basically just swapping css classes randomly on the banner element, on each reload.

Many thanks.

Upvotes: 0

Views: 2004

Answers (4)

Franz
Franz

Reputation: 744

Since you specifically asked for assigning a CSS class, there is a jquery function to do this:

$(function() {
   var id = Math.floor(Math.random() * 10);
   $("#banner").addClass("className" + id);
}

There are also a few more functions related to this, you can find them documented here: http://docs.jquery.com/Attributes

Upvotes: 2

leepowers
leepowers

Reputation: 38298

Sure thing! A script like this should work:

$(document).ready(function() {
 var ad_urls= ['image1.png', 'image2.jpg'];
 var i= Math.floor(Math.random()*ad_urls.length) - 1;
 $('#image_to_update').attr('src', ad_urls[i]);
});

Then, when you want a new ad you can just update the ad_urls array.

Upvotes: 2

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

Using Math.random() you can generate a number between 0 and N (N being the number of your available banners) and then show banner_i ( 0 <= i <=N ).

To generate the number, you can do something like this :

var N = 10; /* This is the maximum myBannerNumber can get */
var myBannerNumber = Math.floor(Math.random()*N);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

If you want to swap images on each page reload, then you probably need to do this using server side script instead of javascript. Another option is to apply a random css when the DOM is ready:

$(function() {
    // Get a random number between 1
    var id = 1 + Math.floor(Math.random() * 11);
    $('banner').css('background-image', 'url(/images/image' + id + '.jpg)');
});

Upvotes: 1

Related Questions