Skip to content

Instantly share code, notes, and snippets.

@webdesignberlin
Created February 24, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save webdesignberlin/34af9558ad750d70e699 to your computer and use it in GitHub Desktop.
Save webdesignberlin/34af9558ad750d70e699 to your computer and use it in GitHub Desktop.
Viewport Tracking
// via: https://github.com/philipwalton/blog/blob/03452d29533cbc85fe863b5917f43cf1638a8236/_scripts/analytics.js#L7-L42
var breakpoints = {
xs: '(max-width: 419px)',
sm: '(min-width: 420px) and (max-width: 569px)',
md: '(min-width: 570px) and (max-width: 799px)',
lg: '(min-width: 800px) and (max-width: 999px)',
xl: '(min-width: 1000px)'
};
function trackBreakpoints() {
// Do nothing in browsers that don't support `window.matchMedia`.
if (!window.matchMedia) return;
// Prevent rapid breakpoint changes for all firing at once.
var timeout;
Object.keys(breakpoints).forEach(function(breakpoint) {
var mql = window.matchMedia(breakpoints[breakpoint]);
// Set the breakpoint on pageload.
if (mql.matches) {
ga('set', 'dimension1', breakpoint);
}
// Update the breakpoint as the matched media changes, and send an event.
mql.addListener(function(mql) {
if (mql.matches) {
clearTimeout(timeout);
timeout = setTimeout(function() {
ga('set', 'dimension1', breakpoint);
ga('send', 'event', 'Breakpoint', 'change', breakpoint);
}, 1000);
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment