Responsive design is without-a-doubt the future for web designers, but I came across a problem the other day with a responsive application I was working on.
I had to create a scroller using jQuery that scrolled through a number of news items. There are basically three items displayed in the viewport at any one time, so what happens when the media queries kick in and drop it down to two items to save space on the page? The jQuery would contine to scroll the three items which obviously skipped over one.
This led to an interesting question: How can you calculate the number of items in a flowing line on a responsive web page? The number of items on a page will obviously change depending on the amount of horizontal space available. So how can we know when the number of items in a line changes?
How about calculating the offset of the first row of items? That way we know the distance they should be from the top of the page, if we iterate through the items and count as we go, we can measure the offset, check it against the first item in the list and then when it doesn’t match we know we’ve moved to a different row. We break the loop and our count accurately reflects the number of items on the line.
Here’s the CodePen I’ve put together for it: