Author: Benjamin Joffe, Web Applications, Opera Software ASA
This JavaScript file contains a single function testMediaQuery()
, which takes a single string as an argument. 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 which satisfies the given query.
This function can be used in any browser which supports media queries.
See JSDoc for this library.
Media queries and device capabilities are currently not exposed to JavaScript directly. Use this library to detect the capabilities of the browser and adapt your web page or widget accordingly. An example is when the browser is running on a wide or small screen, on a tv or a handheld, like a mobile phone or PDA. In the latter cases memory and CPU power may be sparse or network connections slow and unstable. By detecting the capabilities of the browser, you can can tweak how much you cache data, how often you refresh the page, if a widget needs to be resized to fit the screen or something similar.
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)');
The function adds an invisible div
element to document body. A 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 indeed been applied to the div
element in the current mode. Finally, both elements are removed from the DOM.