If you haven’t read Ethan’s article, stop now, read it, and then come back here.
Recently, I was working on a secondary navigation with two sections. At media queries for smaller sized screens, the navigation had links to show and hide each section using jQuery animations. This posed a problem, however. After they were hidden, jQuery left
style="display: none" on the elements. After resizing the browser and jumping to a media query for a larger sized screen, these elements should have been shown without the need for the additional links, but they were hidden because of the inline style.
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29|| |
Now, I know that everyone likes to say that only developers change their browser sizes to see how things respond. There are real problems with this type of thinking. What if the user maximizes their window or makes it smaller based on the content? This might switch media queries, triggering a break in the secondary navigation. Here's another example that is pretty relevant – what if the controlling media query is somewhere around 900px? A simple orientation change of an iPad would cause these navigation elements to disappear. Oops. Do you care now?
The solution to this problem lies in the elusive
matchMedia method; it provides events triggered by media queries.
In order to run code based on media queries, I'm using
mediaCheck (a wrapper I've written around
matchMedia to fire events when entering or leaving a designated media query) to trigger the cleanup code when entering larger media queries.
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23|| |
Now when the 600px media query is fired, it will remove the
style attributes and all is well with the secondary nav.
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24|| |
Take it out for a test drive, kick the tires, and look under the hood. Feel free to ask questions and contribute, and let's move the web forward together.