I have written this small function in Javascript for changing the padding on an element in HTML. It works well, however, I wonder if there is a better way to write it without so many if statements?
window.addEventListener("resize", navPadding);
function navPadding() {
let width = window.innerWidth;
if(width < 1200){
navDesktop.style.padding = "unset"
} else
if(width > 1200 && width < 1300){
navDesktop.style.padding = "0 19% 0 5.5%"
} else
if(width > 1300 && width < 1400){
navDesktop.style.padding = "0 19% 0 8.5%"
} else
if(width > 1400 && width < 1500){
navDesktop.style.padding = "0 19% 0 11.5%"
} else
if(width > 1500 && width < 1600){
navDesktop.style.padding = "0 19% 0 14%"
} else
if(width > 1600 && width < 1700){
navDesktop.style.padding = "0 19% 0 16%"
} else
if(width > 1700 && width < 1800){
navDesktop.style.padding = "0 19% 0 18%"
} else
if(width > 1800 && width < 1900){
navDesktop.style.padding = "0 19% 0 19%"
} else
if(width > 1900 && width < 2000){
navDesktop.style.padding = "0 20% 0 21%"
};
};
navPadding();
1 Answer 1
That huge if/else
conditional could be converted to for
loop with break
statement.
Assuming 1200
and 2000
as range's lower/upper boundaries.
Padding bottom-left value has the most variation depending on width
.
That fixed variation can be declared as predefined array:
const paddingSteps = [5.5, 8.5, 11.5, 14, 16, 18, 19, 21];
The final concise implementation:
const paddingSteps = [5.5, 8.5, 11.5, 14, 16, 18, 19, 21];
function navPadding() {
let width = window.innerWidth;
if (width < 1200) {
navDesktop.style.padding = "unset";
return;
}
for (i = 1200; i <= 2000; i += 100) {
if (width >= i && width <= i + 100) {
padRight = (width >= 1900) ? 20 : 19;
navDesktop.style.padding = `0 ${padRight}% 0 ${paddingSteps[i % 1200 / 100]}%`;
break;
}
}
}
navPadding();
-
1\$\begingroup\$ Very clever, thank you very much! It works as expected if I just plug it in my code and cuts the number of lines in half. \$\endgroup\$Smlok– Smlok2019年12月19日 10:58:03 +00:00Commented Dec 19, 2019 at 10:58