A jQuery plugin for responsive media query events.
mediaquery.js
jQuery
core.js
Media Query can track global changes to screen size based on an existing grid system. This is useful when many elements need to be resized at any change to the target screen size. Start by configuring the dimensions to be tracked by passing arrays at initialization. These arrays should contain the target width and/or heights to react to:
$.mediaquery({
minWidth : [ 320, 500, 740, 980, 1220 ],
maxWidth : [ 1220, 980, 740, 500, 320 ],
minHeight : [ 400, 800 ],
maxHeight : [ 800, 400 ]
});
After initializing, simply listen for the mqchange.mediaquery
event:
$(window).on("mqchange.mediaquery", function(e, state) {
console.log(state.minWidth, state.maxWidth, state.minHeight, state.maxHeight);
});
Note: In the example above, the mqchange.mediaquery
event will be fire twice for each breakpoint. This is because Mediaquery will respond to both the min-width
and max-width
changes.
Media Query can also bind events to specific media query changes for more fine grain control:
$.mediaquery("bind", "mq-key", "(min-width: 740px)", {
enter: function() {
...
},
leave: function() {
...
}
});
To unbind a Media Query:
$.mediaquery("unbind", "mq-key");
When supporting IE, a HTML5 enabler and matchMedia polyfill (IE 8, IE 9) are required.
Set instance options by passing a valid object at initialization, or to the public defaults
method.
Name | Type | Default | Description |
---|---|---|---|
minWidth |
0 |
Array of min-widths | |
maxWidth |
Infinity |
Array of max-widths | |
minHeight |
0 |
Array of min-heights | |
maxHeight |
Infinity |
Array of max-heights | |
unit |
string |
'px' |
Unit to use when matching widths and heights |
## Events
Events are triggered on the window
, unless otherwise stated.
Event | Description |
---|---|
mqchange.mediaquery |
Change to a media query match; Triggered on window |
## Methods
Methods are publicly available, unless otherwise stated.
Binds callbacks to media query matching.
$.mediaquery("bind", "key", "(min-width: 500px)", { ... });
Name | Type | Default | Description |
---|---|---|---|
key |
string |
Instance key | |
media |
string |
Media query to match | |
data |
object |
Object containing 'enter' and 'leave' callbacks |
Extends plugin default settings; effects instances created hereafter.
$.media query("defaults", { ... });
Name | Type | Default | Description |
---|---|---|---|
options |
object |
{} |
New plugin defaults |
Returns the current state.
var state = $.mediaquery("state");
Unbinds all callbacks from media query.
$.mediaquery("unbind", "key");
Name | Type | Default | Description |
---|---|---|---|
key |
string |
Instance key | |
media |
string |
Media query to unbind; defaults to all |