How To See Multiple Elements Styling Change With A Loop?
If I'm using this I only see the last div change color, how can I make the loop so I can see every div change color, see 1 turn red, then 2, then 3 and so on until 5 ?
Solution 1:
You need setTimeout
for(let i = 0; i <= 5; i++){
setTimeout(() => {
$('div').css({'color': 'black'})
$('#' + i).css({'color': 'red'})
}, 250 * i);
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid='1'>1</div><divid='2'>2</div><divid='3'>3</div><divid='4'>4</div><divid='5'>5</div><divid='6'>6</div><divid='7'>7</div>
Solution 2:
Your loop is happening almost instantly. Use setTimeout
/setInterval
to add some time to see changes:
var i = 1;
var interval;
interval = setInterval(loop, 1000);
functionloop() {
$('div').css({'color': 'black'});
$('#' + i).css({'color': 'red'});
i++;
if (i > 5) {
clearInterval(interval);
}
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid='1'>1</div><divid='2'>2</div><divid='3'>3</div><divid='4'>4</div><divid='5'>5</div><divid='6'>6</div><divid='7'>7</div>
Solution 3:
Your loop is happening almost instantly. Use setTimeout
/setInterval
to add some time to see changes:
setInterval(function() {
var $active = $('ul.cur-item li.active').removeClass('active').next('li');
$active.removeClass('active');
if (!$active.length) $active = $active.prevObject.siblings(':first');
$active.addClass('active');
}, 2000);
ul.cur-itemli.active {
font-weight: 700;
display: block;
color: red;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="cur-item"><liclass="active">1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
Post a Comment for "How To See Multiple Elements Styling Change With A Loop?"