0

I have written this with the intention of randomising a background image each time a user visits a site. I had to use Ajax as the image is being used as a background image in css with some animations.

var images = [
  '1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];

var randomNumber = Math.floor(Math.random() * images.length);
var randomImage = "img/backgrounds/" + randomNumber + ".jpg";
jQuery.ajax(randomImage);

$(document).ajaxComplete(function() {
    $('.cover').css({ 'background-image': 'url(' + randomImage + ')' }).addClass('loaded');
});

My problem is that some images seem to be used a lot more often that others and image number 6 never shows?

I was hoping someone who is more comfortable in Javascript might be able to shed some light on this for me.

Thanks in advance, Sam

3
  • 5
    Try naming images from 0.jpg to 5.jpg Commented Nov 28, 2014 at 11:45
  • 2
    or Math.floor(Math.random() * (images.length + 1)) Commented Nov 28, 2014 at 11:46
  • Thanks Guys, I ended up implementing something simular Commented Nov 28, 2014 at 12:45

2 Answers 2

2

The range of variable randomNumber is 0 to 5 (inclusive). They are the indexes where you want to fetch the value from the array images:

var randomImage = "img/backgrounds/" + images[randomNumber];
Sign up to request clarification or add additional context in comments.

Comments

1

change your random number as var randomNumber = Math.floor((Math.random() * images.length)+1);

1 Comment

This is what I ended up doing, Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.