views:

56

answers:

2

I'm trying to rewrite this as a for loop; my attempt below failed. Any ideas?

jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame()
    if ($(window).width() < 232){
        $("#grid-content").css( 'width', '232px' );
    }else if ($(window).width() < 458){
        $("#grid-content").css( 'width', '232px' );
    }else if ($(window).width() < 684){
        $("#grid-content").css( 'width', '458px' );
    }else if ($(window).width() < 910){
        $("#grid-content").css( 'width', '684px' );
    }else if ($(window).width() < 1136){
        $("#grid-content").css( 'width', '910px' );
    };
};

The result is the div (#grid-content) is really wide around 3000px, regardless of window size.

jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame()
    for (x=232;x<=3000;x=x+226){
        if ($(window).width() < x ){
            $("#grid-content").css( 'width', x +'px' );
        };
    };
};
+2  A: 

You need to exit the loop on the first match so it doesn't continue until the end, like this:

jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame() {
    for (x=232;x<=3000;x=x+226){
        if ($(window).width() < x ){
            $("#grid-content").css( 'width', x +'px' );
            break; //add this
        }
    }
}

You can optimize a bit though, like this:

jQuery(window).bind("load resize", function () {
    var w = $(window).width();
    for (var x=232;x<=3000;x+=226) {
        if (w < x ) {
            $("#grid-content").width(x);
            break;
        }
    }
});
Nick Craver
+1 while @bobince showed a simpler solution, you correctly pointed out why his for loop fails.
galambalazs
+6  A: 

You don't need a loop to round-down-to-discrete-steps, it's simple arithmetic.

function resizeFrame() {
    var w= $(window).width();
    w-= (w-6) % 226;
    if (w<232) w= 232;
    $('#grid-content').width(w);
}
bobince
Is it me, or does the expected result from OP's `if()` statement(s) seem out of sync with the expected result from the `for()` loop?
patrick dw
@patrick: oh, good point, I hadn't spotted that! The round-down behaviour in the `if` does seem much more likely to be useful than rounding up. Changed answer to round down instead of up. (Also discarded the `3000` check since my guess is this and the 1136 limit in the `if` case are merely arbitrary upper bounds.)
bobince
thanks. if you have the time could you explain this a little?
ThomasReggi
`n-= n%chunk` is an idiom to round down to the nearest multiple of `chunk`. It uses the `%` operator to divide by `chunk` and take the remainder; subtracting the remainder from the original value leaves the rounded-down multiple. (The `-6` is needed to align the chunks so that they're at `6, 232, ...` instead of `0, 226, ...`.)
bobince