Raffy T Lawrence Raffy T Lawrence - 1 month ago 5
PHP Question

PHP/jQuery: Randomly display single div from loop

I have a loop that contains dynamic and multiple divs. I only need to display single div randomly and when refreshing the page it should change the div dynamically

Like for example PHP

for($i= 1; $i<=5; $i++){
echo'<div class="">
this is div '.$i.'
</div>';
}


Output will be

1
2
3
4
5


But i want to only display single div. Other should hide using jquery or php, so whenever i refresh the page it should display any number in the loop randomly

//output-->
//this is div 2

Answer

First need to calculate the length of div. Then we hide all other elements and show just the randomly chosen one.

$('.random').hide().eq(Math.floor(Math.random()*$('.random').length)).show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="random">1</div>
<div class="random">2</div>
<div class="random">3</div>
<div class="random">4</div>
<div class="random">5</div>

Comments