Skip to content

Instantly share code, notes, and snippets.

@peterwilsoncc
Last active December 17, 2015 11:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterwilsoncc/5602741 to your computer and use it in GitHub Desktop.
Save peterwilsoncc/5602741 to your computer and use it in GitHub Desktop.
Using media queries in JavaScript (based around http://adactio.com/journal/5429/)
#js-mediaquery {
overflow: hidden;
width: 1px;
height: 1px;
position: absolute;
top: -999999em;
left: auto;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
}
#js-mediaquery:after {
content: '320';
display: none;
}
@media only screen and (min-width: 768px) {
#js-mediaquery:after {
content: '768';
}
}
@media only screen and (min-width: 1024px) {
#js-mediaquery:after {
content: '1024';
}
}
<!DOCTYPE html>
<html class="no-js">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Media queries in JavaScript</title>
<script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>
<link rel="stylesheet" href="css.css">
</head>
<!--[if lt IE 8]><body class="old-ie"> <![endif]-->
<!--[if gt IE 7]><!--><body> <!--<![endif]-->
<div id="js-mediaquery"></div>
<script src="script.js"></script>
</body>
</html>
console = window.console || {};
console.log = window.console.log || function(log){alert(log);};
var PWCC = window.PWCC || {};
PWCC.site = function(window, document) {
var media_query = {
elem: document.getElementById("js-mediaquery"),
active: 0
};
// DOC.ready event
detect_media_query();
// resize event
if (window.addEventListener) {
window.addEventListener('resize', detect_media_query, false);
}
//functionality
function detect_media_query() {
var changed = false,
active = media_query.active,
detected = 320, //default
style;
if ( window.getComputedStyle ) {
style = window.getComputedStyle(media_query.elem,':after').getPropertyValue('content');
if (style.indexOf("320") !=-1) {
detected = 320;
}
else if (style.indexOf("768") !=-1) {
detected = 768;
}
else if (style.indexOf("1024") !=-1) {
detected = 1024;
}
}
media_query.active = detected;
if ( detected != active ) {
// run faux change event
on_media_query_change();
}
}
function on_media_query_change() {
console.log( media_query.active );
}
}(this, this.document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment