Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple way to track media query use in your JavaScript
// Get the active Media Query as defined in the CSS
// Use the following format:
// #getActiveMQ-watcher { font-family: "default"; }
// @media only screen and (min-width:20em){ #getActiveMQ-watcher { font-family: "small"; } }
// etc.
window.getActiveMQ = function() {
// Build the watcher
var $watcher = document.createElement('div'),
// alias getComputedStyle
computed = window.getComputedStyle,
// Regexp for removing quotes
re = /['"]/g;
// set upt the watcher and add it to the DOM
$watcher.setAttribute( 'id', 'getActiveMQ-watcher' );
$watcher.style.display = 'none';
document.body.appendChild( $watcher );
// For modern browsers
if ( computed )
{
window.getActiveMQ = function() {
return computed( $watcher, null ).getPropertyValue( 'font-family' ).replace( re, '' );
};
}
// For everything else
else
{
window.getActiveMQ = function() {
return 'unknown';
};
}
return window.getActiveMQ();
};
(function($,window){
window.getActiveMQ = function()
{
$('<div id="getActiveMQ-watcher"></div>')
.appendTo('body')
.hide();
var computed = window.getComputedStyle,
watcher = document.getElementById('getActiveMQ-watcher');
if ( computed )
{
window.getActiveMQ = function()
{
return computed( watcher, null ).getPropertyValue( 'font-family' ).replace(/['"]/g,'');
};
}
else
{
window.getActiveMQ = function()
{
return 'unknown';
};
}
return window.getActiveMQ();
};
}(jQuery, window))
#getActiveMQ-watcher {
font-family: "break-0";
}
@media only screen and (min-width: 20em) {
#getActiveMQ-watcher {
font-family: "break-1";
}
}
@media only screen and (min-width: 30em) {
#getActiveMQ-watcher {
font-family: "break-2";
}
}
@media only screen and (min-width: 48em) {
#getActiveMQ-watcher {
font-family: "break-3";
}
}
/* etc. */
@webstacker

This comment has been minimized.

Copy link

commented Oct 4, 2014

hey, just read about this in netmag. It's something I had done some work on too:

http://codepen.io/webstack/pen/mnbwa

I see you've opted to inject a new element rather than use a pseudo element or existing element. Did you find issues with those techniques?

@aarongustafson

This comment has been minimized.

Copy link
Owner Author

commented Oct 22, 2015

I just prefer the cleanliness of injecting an element.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.