MediaQuery
Responsive media query events.
Demos
Basic
Run callbacks when a media query starts or stops matching. Resize the result to see it change.
<p class="demo_status">
The viewport is <strong class="js-status">…</strong>
</p>
import { MediaQuery, Utils } from 'formstone';
Utils.ready(() => {
let status = document.querySelector('.js-status');
MediaQuery.bind('demo', '(min-width: 600px)', {
enter: () => {
status.textContent = 'at least 600px wide';
document.body.classList.add('is-wide');
},
leave: () => {
status.textContent = 'narrower than 600px';
document.body.classList.remove('is-wide');
},
});
});
body {
padding: 5vh 5vw;
}
.demo_status {
background: var(--color-yellow);
border: var(--border-size) solid var(--color-black);
border-radius: var(--border-size);
padding: 20px;
}
.is-wide .demo_status {
background: var(--color-blue);
}
Methods
Methods are publicly available static methods.
| Name | Description |
|---|---|
.bind() |
Binds callbacks to a media query |
.unbind() |
Unbinds callbacks from a media query |
.bind()
Binds callbacks to a media query.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
key |
string (required) |
'' |
Unique identifier for this binding; binding an existing key to the same media query logs a warning and is ignored |
media |
string (required) |
'' |
Media query string (e.g., '(min-width: 768px)') |
data |
object (required) |
{} |
Object containing enter and/or leave callback functions |
Examples
MediaQuery.bind('mobile', '(max-width: 740px)', {
enter: function() {
console.log('Mobile view');
},
leave: function() {
console.log('Desktop view');
}
});
.unbind()
Unbinds callbacks from a media query.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
key |
string (required) |
'' |
Identifier used with .bind() (exact match) |
media |
string (optional) |
'' |
Specific media query string (omit to unbind from all) |
Examples
MediaQuery.unbind('mobile');
MediaQuery.unbind('mobile', '(max-width: 740px)');