1
\$\begingroup\$

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();
Heslacher
50.9k5 gold badges83 silver badges177 bronze badges
asked Dec 19, 2019 at 7:31
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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();
answered Dec 19, 2019 at 8:51
\$\endgroup\$
1
  • 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\$ Commented Dec 19, 2019 at 10:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.