Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
画面のスクロール位置を、Google Analyticsのイベントトラッキングに記録する。 記録したい要素のidを配列として関数に渡すと、その要素が画面に表示されたときに記録を残す。
$.extend({
attachScrollEventTracking: function(eventcategory, pagePartsIdList) {
var pageParts = {};
var windowHeight = $(window).height();
$.each(pagePartsIdList, function(key, pagePartsId){
//console.log(pagePartsId);
var target = $("#" + pagePartsId);
if (target.length > 0) {
pageParts[pagePartsId] = target.offset().top;
}
});
//console.log(pageParts);
var isFinish = false;
$(document).bind("scroll", function(event) {
if (!isFinish) {
var scrollTop = $(document).scrollTop() + windowHeight;
//console.log(scrollTop);
isFinish = true;
$.each(pageParts, function(pagePartsId, value){
if (value < scrollTop) {
//console.log(['_trackEvent', eventcategory, 'scroll', pagePartsId, value, true]);
_gaq.push(['_trackEvent', eventcategory, 'scroll', pagePartsId, value, true]);
delete pageParts[pagePartsId];
}
isFinish = false;
});
}
});
}
});
$(document).ready(function() {
// 記録したい要素のidを指定
var pageParts = ["section-1", "section-2", "section-3",
"section-4", "section-5",
"section-6", "section-7", "section-8", "section-9"];
$.attachScrollEventTracking('tracking_event_category', pageParts);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment