Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this JavaScript/jQuery code shorter

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');
}
like image 597
Clams Are Great Avatar asked Jan 07 '23 15:01

Clams Are Great


1 Answers

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');
like image 67
Tushar Avatar answered Jan 19 '23 08:01

Tushar