I don’t really understood what you really want, but, here’s a solution to achieve your task when the page is loaded.
So, when the page is loaded, we fetch all the div
s containing the class nprotagonistas__bg
and then randomly we’ll assign the class hover
to only one of the div
s. This will be done depending on the number of div
s containing the class nprotagonistas__bg
and we’ll use the built-in random
method to get a random number that will be used as the index of the selected div
(the random number is the index on the page of the div
that’s selected to get the hover
class, so reloading the page ends in getting another random div
).
With all that being said, here’s a snippet to illustrate:
In the snippet, the
hover
class adds a redbackground
to the element that has this class.
// waiting till the page is loaded by listening to the 'load' event on the 'window' object.
window.addEventListener('load', function() {
/**
* fetch all the divs with the class 'nprotagonistas__bg'.
* getting the number of these divs on the page(how many div is there).
* using the 'random' method we'll get a random number that is >= 0 and <= the number of the divs.
**/
var divs = document.querySelectorAll('div.nprotagonistas__bg'),
l = divs.length,
r = Math.ceil(Math.random() * l) - 1;
// assign the 'hover' class to a div depending on thethe random number.
divs[r].classList.add('hover');
});
.nprotagonistas__bg {
/* just to make the divs visible on the page */
height: 50px;
border: 2px solid green;
}
.nprotagonistas__bg.hover{
background: red;
}
<div class="nprotas">
<div class="container">
<div class="row">
<div class="col-6">
<div class="nprotagonistas">
<div class="nprotagonistas__bg grey">
</div>
<div class="nprotagonistas__content lectores">
</div>
</div>
</div>
<div class="col-6">
<div class="nprotagonistas">
<div class="nprotagonistas__bg white">
</div>
<div class="nprotagonistas__content controladores">
</div>
</div>
</div>
<div class="col-6">
<div class="nprotagonistas">
<div class="nprotagonistas__bg black">
</div>
<div class="nprotagonistas__content videointercomunicacion">
</div>
</div>
</div>
<div class="col-6">
<div class="nprotagonistas">
<div class="nprotagonistas__bg red">
</div>
<div class="nprotagonistas__content aplicacion">
</div>
</div>
</div>
</div>
</div>
Learn more about the
random
method.Learn more about the
ceil
method.Learn more about the
addEventListener
method.
Hope I pushed you further.
4
solved add unique class in randomly position to the div with the same class