views:

573

answers:

4

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.

+1  A: 

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)');
});
Darin Dimitrov
+1  A: 

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);
Soufiane Hassou
+1  A: 

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.

pygorex1
+1  A: 

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

Franz