Media Query library
testMediaQuery(), which takes a single string as an argument (see here for a test file.) The string can contain any valid media query, including media types and media features. It returns a boolean true/false based on whether or not the browser is in a mode that satisfies the given query.
This function can be used in any browser that supports media queries. See the following JSDoc output for the library's documentation and code.
What can you use it for?
You should avoid calling this function multiple times to test the same thing, as the function call may cause a reflow of the layout on the page. Instead, test once and store the results in a variable.
The following code will test if the browser is in a handheld mode and store the results in a variable. The typical example is mobile phones, PDAs and similar.
var handheld = testMediaQuery('handheld');
In the following example a combination of a media type and a media feature query is used. The
if block will be executed if the browser is in a TV mode and has a maximum available height of 400 pixels.
var test = testMediaQuery('tv and (max-height: 400px)');
How it works
The function adds an invisible
div element to the document
style element is added with the given media query and a
display:none; rule on the
div. Then the function checks if the style has been applied properly to the
div element in the current mode. Finally, both elements are removed from the DOM.
This article is licensed under a Creative Commons Attribution, Non Commercial - Share Alike 2.5 license.