Federico Ferrari Federico Ferrari - 1 month ago 6
CSS Question

Assign a random class different to every img

Right now this code gives all the imgs the same random class.

How can I give at each image a different random class?

Thanks for any help.



$(document.body).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
$('img').addClass('img' + randomNumber);
});

.img1{max-height:10px}
.img2{max-height:40px}
.img3{max-height:70px}
.img4{max-height:100px}
.img5{max-height:130px}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">




Answer

If you want each img to have unique random class, you can create an array from a set:

$(document.body).ready(function () {
    var $imgs = $('img');
    var len = $imgs.length;
    
    var set = new Set;
    while (set.size != len) {
        set.add((Math.random() * len | 0) + 1);
    }
    var arr = [...set];
    $imgs.each(function(pos) { $(this).addClass('img' + arr[pos]) });
});
.img1{height:10px}
.img2{height:40px}
.img3{height:70px}
.img4{height:100px}
.img5{height:130px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">
<img src="http://i.imgur.com/YeDYzSR.png">

Comments