Skip to content

Instantly share code, notes, and snippets.

@mistakster
Created May 5, 2014 08:54
Show Gist options
  • Save mistakster/a46b0dbaa2e236c19383 to your computer and use it in GitHub Desktop.
Save mistakster/a46b0dbaa2e236c19383 to your computer and use it in GitHub Desktop.
Wait for desired environment (mobile or desktop)
var Environment = (function () {
var _mqDesktop, _mqMobile;
function getMobileMediaQuery() {
return _mqMobile || (_mqMobile = window.matchMedia("(max-width: 719px)"));
}
function getDesktopMediaQuery() {
return _mqDesktop || (_mqDesktop = window.matchMedia("(min-width: 720px)"));
}
function isMobile() {
return !!(window.matchMedia && getMobileMediaQuery().matches);
}
function isDesktop() {
return !!(window.matchMedia && getDesktopMediaQuery().matches);
}
function once(mq, callback) {
function handler() {
mq.removeListener(handler);
callback();
}
mq.addListener(handler);
}
function getStyle(el, cssProperty) {
return (getComputedStyle !== "undefined") ?
getComputedStyle(el)[cssProperty] : el.currentStyle[cssProperty];
}
function waitUntil(value, cb) {
var body, detector = document.querySelector(".style-detector");
if (!detector) {
detector = document.createElement("div");
detector.className = "style-detector";
body = document.getElementsByTagName("body")[0];
body.insertBefore(detector, body.firstChild);
}
var i = 100;
(function loop() {
var v = getStyle(detector, "zIndex");
if (v != value) {
i = i - 1;
if (i >= 0) {
setTimeout(loop, 250);
} else {
cb();
}
} else {
cb();
}
}());
}
function waitForEnvironment(condition, mq, callback, sure, zIndex) {
var handler = function () {
if (sure) {
waitUntil(zIndex, callback);
} else {
callback();
}
};
if (condition()) {
handler();
} else {
once(mq(), handler);
}
}
return {
isMobile: isMobile,
isDesktop: isDesktop,
waitForMobile: function (callback, sure) {
waitForEnvironment(isMobile, getMobileMediaQuery, callback, sure, 1);
},
waitForDesktop: function (callback, sure) {
waitForEnvironment(isDesktop, getDesktopMediaQuery, callback, sure, 2);
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment