Reputation: 183
I want to change margin-bottom based on table rows. But the else if statement always stops at the first else if, which is margin-bottom:50px. Below is my code. Someone please help?
jQuery(document).ready(function($) {
if ($('table.variations > tbody > tr').length = 0){
$('div[itemprop="description"]').css('margin-bottom','0');
} else if ($('table.variations > tbody > tr').length = 1){
$('div[itemprop="description"]').css('margin-bottom','50px');
} else if ($('table.variations > tbody > tr').length = 2){
$('div[itemprop="description"]').css('margin-bottom','100px');
} else {
$('div[itemprop="description"]').css('margin-bottom','200px');
}
})
Upvotes: 0
Views: 41
Reputation: 707386
Comparisons should be ==
or preferably ===
, not =
. You are assigning, not comparing when you use =
.
It should be this:
if ($('table.variations > tbody > tr').length === 0){
$('div[itemprop="description"]').css('margin-bottom','0');
} else if ($('table.variations > tbody > tr').length === 1){
$('div[itemprop="description"]').css('margin-bottom','50px');
} else if ($('table.variations > tbody > tr').length === 2){
$('div[itemprop="description"]').css('margin-bottom','100px');
} else {
$('div[itemprop="description"]').css('margin-bottom','200px');
}
Though, it can be made a lot more efficient like this:
var margin;
switch($('table.variations > tbody > tr').length) {
case 0:
margin = 0;
break;
case 1:
margin = 50;
break;
case 2:
margin = 100;
break;
default:
margin = 200;
break;
}
$('div[itemprop="description"]').css('margin-bottom', margin + "px");
Notice how there is no copied code and no selectors being evaluated more than once.
Another way of doing it would be to use a lookup table:
var marginValues = {0: "0px", 1: "50px", 2: "100px"};
var margin = marginValues[$('table.variations > tbody > tr').length];
if (!margin) {
margin = "200px";
}
$('div[itemprop="description"]').css('margin-bottom', margin);
Or, this can even be done with a computation:
var margin, len = $('table.variations > tbody > tr').length;
if (len <= 2) {
margin = len * 50;
} else {
margin = 200;
}
$('div[itemprop="description"]').css('margin-bottom', margin + "px");
Upvotes: 1