I want to show div with different class with different time. for e.g my div has to show for 2000 ms class will be 'one' then for div has to show for 4000 ms class will be be 'two', then div has to show for 3000 ms class will be 'three'. i am using array to addClass with timer. but array short out from lower value to higher value. i dont want that. Please help me in this problem.
html code
var text = ['one', 'two', 'three', 'four'];
var timeleft =['5000','2000','4000','3000'];
$.each (timeleft, function(i, timeleft){
setTimeout ( function(){
$('#change').addClass(text[i]);
$('#change').text(text[i]);
console.log(text[i]);
}, timeleft);
})
.one {
background-color: red;
font-size: 100px;
text-align: center;
}
.two {
background-color: yellow;
font-size: 100px;
text-align: center;
}
.three {
background-color: green;
color: white;
font-size: 100px;
text-align: center;
}
.four {
background-color: rebeccapurple;
color: white;
font-size: 100px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="" id="change"> change</div>
</div>
You can use queue
and delay
for this:
var text = ['one', 'two', 'three', 'four'];
var timeleft = ['5000', '2000', '4000', '3000'];
$.each(timeleft, function(i, timeleft) {
$('#change')
.queue(function() {
$(this)
.text(text[i])
.addClass(text[i])
.dequeue();
})
.delay(timeleft);
});
.one {
background-color: red;
font-size: 100px;
text-align: center;
}
.two {
background-color: yellow;
font-size: 100px;
text-align: center;
}
.three {
background-color: green;
color: white;
font-size: 100px;
text-align: center;
}
.four {
background-color: rebeccapurple;
color: white;
font-size: 100px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="" id="change">change</div>
</div>