Hoping someone can help with this…
I am trying to set up a page to randomly display Div content from several Div blocks onClick. I have some base code I found and have been playing with but I can’t work out how to modify it to display multiple Divs at once.
var random = document.getElementsByClassName('random')[0];
var menuCovers = document.getElementsByClassName('menu_cover2');
function openRandomMenu() {
for (var i = 0; i < menuCovers.length; i++) {
if (menuCovers[i].classList.contains('visible')) {
var skip = i;
menuCovers[i].classList.remove('visible');
menuCovers[i].classList.add('invisible');
}
}
var randomNumber = skip;
while (randomNumber === skip) {
randomNumber = Math.floor(Math.random() * menuCovers.length);
}
menuCovers[randomNumber].classList.remove('invisible');
menuCovers[randomNumber].classList.add('visible');
}
random.addEventListener('click', openRandomMenu, false);
.visible {
display: block;
}
.invisible {
display: none;
}
.bloc {
padding: 20px;
border: 1px solid #ff0000;
}
.offset {
margin-top: 200px;
}
<div>
<p class="random bloc">Random</p>
<div class="menu_cover invisible bloc">One</div>
<div class="menu_cover invisible bloc">Menu two</div>
<div class="menu_cover invisible bloc">Menu three</div>
<div class="menu_cover invisible bloc">Menu four</div>
<div class="menu_cover invisible bloc">Menu five</div>
<div class="menu_cover invisible bloc">Menu six</div>
</div>
<div>
<div class="menu_cover2 invisible bloc offset">Menu Xone</div>
<div class="menu_cover2 invisible bloc offset">Menu Xtwo</div>
<div class="menu_cover2 invisible bloc offset">Menu Xthree</div>
<div class="menu_cover2 invisible bloc offset">Menu Xfour</div>
<div class="menu_cover2 invisible bloc offset">Menu Xfive</div>
<div class="menu_cover2 invisible bloc offset">Menu Xsix</div>
</div>
With the above, as per the original example, I can get one of the Div blocks to display, in this case ‘menu_cover2’ but not the first.
Any ideas out there?
2
Answers
You mean something like this?
I am assuming the two sets have the same number of divs
If the list of divs is of different length we can do this
.visible
rule. Also, use rather a.is-hidden
instead of.invisible
(which would imply visibility:hidden instead of display:none )Element.classList.toggle("is-hidden", boolean)
on both your setsrand(min, max)
that returns a float random number in range0, NodeList.length
, and then useMath.floor(rn)
or~~rn
to round it down<button>
is something should be a user-action element, not<p>