Is there a way to loop this four times to make it shorter? I am trying to change the class from standing to sitting and then back again one at a time.
if(sitting > 0) {
$('.standing:first-of-type').removeClass('standing').addClass('sitting');
} else {
$('.sitting:first-of-type').removeClass('sitting').addClass('standing');
}
if(sitting > 1) {
$('.standing:nth-of-type(2)').removeClass('standing').addClass('sitting');
} else {
$('.sitting:nth-of-type(2)').removeClass('sitting').addClass('standing');
}
if(sitting > 2) {
$('.standing:nth-of-type(3)').removeClass('standing').addClass('sitting');
} else {
$('.sitting:nth-of-type(3)').removeClass('sitting').addClass('standing');
}
if(sitting > 3) {
$('.standing:nth-of-type(4)').removeClass('standing').addClass('sitting');
} else {
$('.sitting:nth-of-type(4)').removeClass('sitting').addClass('standing');
}
You can use :lt
and :gt
selectors.
:lt(index)
select all elements at an index less than index
within the matched set. :gt(index)
select all elements at an index greater than index
within the matched set.From jQuery Docs
As the class sitting
should be added to all the elements having class .standing
whose index
is less than the sitting
variable value, :lt
selector can be used with the variable sitting
to select such elements. Then addClass()
and removeClass()
can be used on the jQuery set of elements to add and remove the passed classes respectively.
$('.standing:lt(' + sitting + ')').removeClass('standing').addClass('sitting');
$('.sitting:gt(' + sitting + ')').removeClass('sitting').addClass('standing');
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