I'm new to javascript/jQuery. Is there a way to make this code shorter?
else if (players == 6) {
$('#box1').addClass("col-md-4");
$('#box1').removeClass("col-md-6");
$('#box2').addClass("col-md-4");
$('#box2').removeClass("col-md-6");
$('#box3').addClass("col-md-4");
$('#box3').removeClass("col-md-6");
$('#box4').addClass("col-md-4");
$('#box4').removeClass("col-md-6");
$('#box4').removeClass("col-md-offset-4");
$('#box5').addClass("col-md-4");
$('#box5').removeClass("col-md-6");
$('#box6').addClass("col-md-4");
$('#box6').removeClass("col-md-6");
$('#box1').show();
$('#box2').show();
$('#box3').show();
$('#box4').show();
$('#box5').show();
$('#box6').show();
}
You can combine the selectors and apply each method with chaining.
else if (players == 6) {
$('#box1,#box2,#box3,#box4,#box5,#box6')
.addClass("col-md-4")
.removeClass("col-md-6")
.show();
}
Or use attribute starts with the selector.
else if (players == 6) {
$('[id^="box"]')
.addClass("col-md-4")
.removeClass("col-md-6")
.show();
}
else if (players == 6) {
$('.box')
.addClass("col-md-4")
.removeClass("col-md-6")
.show();
}
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