Skip to content

Instantly share code, notes, and snippets.

@aarongustafson
Last active June 27, 2017 03:59
Show Gist options
  • Save aarongustafson/a0558c185264355df359 to your computer and use it in GitHub Desktop.
Save aarongustafson/a0558c185264355df359 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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