I am currently working on credit card UI. I've been trying to randomly change the background-image of multiple divisions(class names are the same). My intention is showing different image randomly for each division on reload the page, but I end up with the same image(random, though) for all target divisions.
Help would be greatly appreciated.
Current code is as below(style is not written here).
<html>
<body>
<div class="card-inner"></div>
<div class="card-inner"></div>
<div class="card-inner"></div>
<script>
window.onload = function () {
var url = [];
url[0] = 'card-bg1.jpg';
url[1] = 'card-bg2.jpg';
url[2] = 'card-bg3.jpg';
var n = Math.floor(Math.random() * url.length);
var elm = document.querySelectorAll('.card-inner');
for (let i = 0; i < elm.length; i++) {
elm[i].style.backgroundImage = 'url(../img/service/' + url[n] + ')';
}
}
</script>
</body>
</html>
Just move
var n = Math.floor(Math.random() * url.length);
inside the loop like this
for (let i = 0; i < elm.length; i++) {
var n = Math.floor(Math.random() * url.length);
elm[i].style.backgroundImage = 'url(../img/service/' + url[n] + ')';
}
How can you expect it will be different if you call it once?
If you want them to be unique, you can use code like this, removing chosen element from urls array each time
function () {
const urls = []
const elm = document.querySelectorAll('.card-inner');
for (let i = 0; i < elm.length; i++) {
if (!urls.length) {
urls.push('card-bg1.jpg', 'card-bg2.jpg', 'card-bg3.jpg');
}
const n = Math.floor(Math.random() * urls.length);
const url = urls.splice(n, 1).pop()
elm[i].style.backgroundImage = 'url(../img/service/' + url + ')';
}
}
PS Looks strange using var and let together. If you use let, then use const for non-changable variables