Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten this JQuery Code

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();
}
like image 272
LeEclipse Avatar asked Nov 30 '25 14:11

LeEclipse


1 Answers

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();
}


Or use a common class for elements and select based on that.
else if (players == 6) {
   $('.box')
        .addClass("col-md-4")
        .removeClass("col-md-6")
        .show();
}
like image 189
Pranav C Balan Avatar answered Dec 02 '25 03:12

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!