Created
February 24, 2015 14:39
-
-
Save webdesignberlin/34af9558ad750d70e699 to your computer and use it in GitHub Desktop.
Viewport Tracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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