Question

I have a list where the li images are floating left and arrange themselves in different numbers of rows depending on window size (using media queries and different img sizes). The vertical spacing between the elements is done by using a bottom margin. However, the list items that wind up on the bottom row don't need a bottom margin on them: it leaves too much space above the footer. I figured out a (probably inefficient) way using JQuery to get rid of the bottom margin on the items on the bottom row:

    bottomMargin();
    window.onresize = bottomMargin;

    function numberOfRows () {
        var noOfRows = 0;
        $('#gallery ul li').each(function() {
            if($(this).prev().length > 0) {
                if($(this).position().top != $(this).prev().position().top)
                    noOfRows++;
            }
            else
                noOfRows++;
        });
        return noOfRows;
    }

    function whichRow() {
        var thisRow = 0;
        $('#gallery ul li').each(function() {
            if($(this).prev().length > 0) {
                if($(this).position().top == $(this).prev().position().top) {
                    $(this).data('row', thisRow);
                }   
                else {
                    thisRow++;
                    $(this).data('row', thisRow);
                }       
            }
            else {
                thisRow++;
                $(this).data('row', thisRow);
            }
        }); 
    }

    function bottomMargin() {                       
        whichRow();
        var totalRows = numberOfRows();
        $('#gallery ul li').each(function () {
            if ($(this).data('row') == totalRows)
                $(this).css('margin-bottom', '0%');
            else
                $(this).css('margin-bottom', '');   
        });
    }

This will work the majority of the time. However, if I resize more than one media query away from where the page loaded, it won't alter the margins on the initial window resize. I have to resize again very slightly before it gets rid of that pesky bottom margin. Why should it take two resizes?

Was it helpful?

Solution

Hmm, sounds like a conflict of you doing math and applying margins before the browser is really done drawing the page, or something else timing related. Try throttling your resize callback:

var resizeTimer = 0;

$(window).on('resize', function() {
  clearTimeout( resizeTimer );
  resizeTimer = setTimeout(bottomMargin, 30);
})

function bottomMargin() {
  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top