Reputation: 1108
At the moment in my game, when it is complete a random image is passed to the "reveal-wrapper" to display at the end.
I still want to do this but instead of doing it this way I would like to add a random class each time to the "revael-wrapper" to make it ".reveal-wrapper .image1" for example. There will be 5 different images and I want it to pick one at random each time.
The code for it at the moment is as follows:
$(document).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
imgPath = ('images/reward-images/' + randomNumber + '.png');
$('.reveal-wrapper').css('background-image', ('url("' + imgPath + '")'));
});
Any ideas how I would add a random class instead?
Upvotes: 2
Views: 1496
Reputation: 3815
Rory has a fine solution, but if you're so curious here's something a little more general:
function add_rand_class (classes, elem) {
$(elem).addClass(classes[Math.random() * classes.length >> 0]);
}
pass the function an array of class strings and the element on which you want the class, and you're good to go.
Upvotes: 0
Reputation: 12294
Since you already have the random numbers, and provided your images have the same filename structure (image1, image2, ect.)
$('.reveal-wrapper').addClass('image' + randomNumber);
Upvotes: 0
Reputation: 337570
You've already got the logic in place, you just need to add the class. Try this:
$(document).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
$('.reveal-wrapper').addClass('image' + randomNumber);
});
All you then need to do is setup the classes in your CSS:
.image1 { background-image: url('images/reward-images/1.png'); }
.image2 { background-image: url('images/reward-images/2.png'); }
.image3 { background-image: url('images/reward-images/3.png'); }
.image4 { background-image: url('images/reward-images/4.png'); }
.image5 { background-image: url('images/reward-images/5.png'); }
Upvotes: 4