'how to alternatively display element1 and element 2 where there is a 50% chance that element 1 is displayed instead of element 2
I am trying to make that 50% chance that element1 is displayed on the screen, and a 50% chance element 2 is displayed on the screen. I have been thinking of a code like this for a while now but can't come up with one. the syntax is below on how I want to use the code.
<div class='parent'>
<div class='child'>
<!--there should be 50% chance element 1 is displayed and equal chance for element 2 to be displayed-->
<element1>
or
<element2>
</div>
<div class='child'>
<element1>
or
<element2>
</div>
<div class='child'>
<element1>
or
<element2>
</div>
<div class='child'>
<element1>
or
<element2>
</div>
</div>
the above code would be displayed in an inline code block like 4 boxes in the same line.
Solution 1:[1]
There is no such thing as an exact 50% but the closest you can get to that is by using JavaScript Math.random() and using an if/else statement on page load. A possible solution is:
<!DOCTYPE html>
<html>
<body>
<div class='child'>
<div id="firstEl" class="el">El1</div>
<div id="secondEl" class="el">El2</div>
</div>
<script>
if( Math.round(Math.random()) == 0){
document.getElementById("firstEl").style.display = "block";
}else{
document.getElementById("secondEl").style.display = "block";
}
</script>
</body>
</html>
CSS:
.el{
display:none;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
