0

I have this piece of code, but I was wondering if there was a way to reduce the amount of lines?

function winResize(w) {
    if (w >= 250 && w < 500 ) { $('body').alterClass('col_*', 'col_1'); }
    if (w >= 500 && w < 750 ) { $('body').alterClass('col_*', 'col_2'); }
    if (w >= 750 && w < 1000 ) { $('body').alterClass('col_*', 'col_3'); }
    if (w >= 1000 && w < 1250 ) { $('body').alterClass('col_*', 'col_4'); }
    if (w >= 1250 && w < 1500 ) { $('body').alterClass('col_*', 'col_5'); }
    if (w >= 1500 && w < 1750 ) { $('body').alterClass('col_*', 'col_6'); }
    if (w >= 1750 && w < 2000 ) { $('body').alterClass('col_*', 'col_7'); }
    if (w >= 2000 && w < 2250 ) { $('body').alterClass('col_*', 'col_8'); }
    if (w >= 2250 && w < 2500 ) { $('body').alterClass('col_*', 'col_9'); }
    if (w >= 2500 ) { $('body').alterClass('col_*', 'col_10'); }
}

This is how I call the function

winResize(window.innerWidth);
1
  • 1
    You should at least use else if and move the body of each line to a separate function to reduce repetition. Commented Jun 17, 2013 at 6:35

1 Answer 1

6

It looks like your intervals are multiples of 250. You can use that to advantage:

function winResize(w) {
    var index = Math.min(10, Math.floor(w / 250));
    if (index > 0) {
        $('body').alterClass('col_*', 'col_' + index);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It didn't seem to work, so I placed an alert(index) inside the if statement, and it returned 10.. Also when I resized, it returned 10..
@Anders - It should behave exactly as your posted code does. What's the value of w when it doesn't work and when you resized? Does your posted code do anything different for the same values of w?
@Anders -- My bad. I replace Math.max with Math.min in my answer. It should now work.

Your Answer

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.