HTML5: discovering the difference in size

We all heard about responsive web design. The idea behind it is simple: The layout of your page adapts to the screen size. That is, on a large screen you might want to show your content with a navigation bar to the left and some advertisement to the right. When the screen and or browser window is smaller, maybe you just show the content and move the navigation bar to the top. Something like that.

I was working on a project just like that. The layout and some functionality had to change when the width of the browser got smaller than 1024 pixels. The layout can be controlled with media queries while the change of functionality can be handled in JavaScript. Sounds simple? It is simple, if you are aware of some differences in how width is measured.

Let look at media queries first. Media queries allow for conditional css rules. By including a query such as @media screen and (max-width: 1024px) {...} we can address screen sizes (actually the content area of the browser) of up to 1024 pixels in width. Css rules defined inside such a query would overwrite rules defined outside. For example, if i like my text to the green for screen sizes larger than 1024 pixels and blue otherwise I would include the following:

.mycolor { color:green;}
@media screen and (max-width: 1024px) { .mycolor { color:blue;} }

The change in functionality can be addressed by a simple if statement. Since the project uses jQuery we used $(window).width() to get the width and if(width>1024) {do_this;} else {do_that;} to decide what to do. So, mission accomplished. Or not?

Well, not quite. We tested the solution and found that the change of layout and the change in functionality don't happen at the same time. When slowly reducing the width of the browser, first the layout changed and a few pixel later the functionality, leaving us with 3 distinct state. Let's look at what we actually measure. The width that is used in the media queries measures the width of the viewport including scroll bar if any. The width returned by $(window).width() on the other side returns of the "content area", that is the viewport minus the size of scroll bar and padding. So there is our difference. Luckily the window object contains another property that we can use: window.innerWidth (note that $(window).innerWidth() does not work). By using innerWidth as a width in our JavaScript we managed to trigger the change in design and functionality.

That's it. I hope this blog was useful. If you have questions or comments, please let me know.

Пожалуйста, обратитесь к странице Уведомление об оптимизации для более подробной информации относительно производительности и оптимизации в программных продуктах компании Intel.