Media Query library

By Benjamin Joffe

Introduction

The Media query library JavaScript file contains a single function 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?

Media queries and device capabilities are currently not exposed to JavaScript directly. You can 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 device, like a tv or a handheld device. In the latter case memory and CPU power may be sparse or network connections slow and unstable. By detecting the capabilities of the browser, you can can tweak things like how much you cache data, how often you refresh the page, and if a widget needs to be resized to fit the screen.

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.

Examples

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 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 been applied properly to the div element in the current mode. Finally, both elements are removed from the DOM.

Resources

This article is licensed under a Creative Commons Attribution, Non Commercial - Share Alike 2.5 license.

Comments

The forum archive of this article is still available on My Opera.

No new comments accepted.