I have 10 divs which were displayed in a random time.
How can I set the last shown div on top (rank first position) each time and not in the html order of the divs?
Here is my code:
var myVar;
function showDiv(){
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval(){
setTimeout(showDiv, 500+ Math.random() * 4000);
}
$(document).ready(function(){
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0,0,0,0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;/* hide initially so that fadIn() fadeOut() will work
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
<div class="notification">5</div>
<div class="notification">6</div>
<div class="notification">7</div>
<div class="notification">8</div>
<div class="notification">9</div>
<div class="notification">10</div>
Here is my fiddle: https://jsfiddle.net/gkq21ppt/3/
EDIT: Idea for a solution
A solution could be, to wrap the divs and set them column-reverse. And then add a JS-code which sets a sequential number as flex order number to every new faded in div. But I have no idea how to do this, with my low JS skills.
So the loop could look like:
Or?
You can try using .prependTo()
What this will do (I think) is remove the active notification and add it back to the container, in the first position. Because of this behaviour, flexbox shouldn't be necessary.
Note this changes the HTML structure.
updated fiddle
var myVar;
function showDiv() {
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).prependTo('.container').fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}
function createRandomInterval() {
setTimeout(showDiv, 500 + Math.random() * 4000);
}
$(document).ready(function() {
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0, 0, 0, 0.2);
margin-bottom: 5px;
text-align: center;
padding-top: 20px;
display: none;
/* hide initially so that fadIn() fadeOut() will work */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="notification">1</div>
<div class="notification">2</div>
<div class="notification">3</div>
<div class="notification">4</div>
<div class="notification">5</div>
<div class="notification">6</div>
<div class="notification">7</div>
<div class="notification">8</div>
<div class="notification">9</div>
<div class="notification">10</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With