Track swipes with Google Analytics

2019-08-03 09:00发布

I have a swipe functionality on my mobile page, and I want to used touchstart, touchend, and touchmove to track the swipe functionality across the device without affecting the scrolling.

Here is my code.

jQuery('.first-frame').bind('touchmove', function(event) {
 _gaq.push(['_trackEvent', 'Landing-Page', 'Swipe-Toggle-Color', '0259_2190']);
});

2条回答
甜甜的少女心
2楼-- · 2019-08-03 09:40

I know you asked for a touchmove, touchend, and touchstart example but I would use a combination of HammerJS (https://github.com/EightMedia/hammer.js/) and custom Google events to take the guess work out of it.

var element = $(".first-frame")[0];

var trackswipe = Hammer(element, {
  drag: false,
  transform: false,
  swipe: true,
  swipeVelocityX: 0 // Adjust to liking...
}).on("swipe", function(event) {
  if (event.gesture.direction === "left") {
    // Track Something
    return false;
  } else if (event.gesture.direction === "right") {
    // Track something else.
    return false;
  }
  return false;
});
查看更多
干净又极端
3楼-- · 2019-08-03 09:52

If it's possible to only monitor the swipeleft and swiperight events in jQuery Mobile instead, do so.

Otherwise, you can set a global variable on the scroll event that resets after, say, 0.2 seconds. Then have the touchmove event check if that variable is set, and if it is, don't trigger Google Analytics.

window.is_scrolling = false; // global variable
window.timeout_id = 0;

window.onscroll = function() {
    window.is_scrolling = true;
    clearTimeout(window.timeout_id);
    window.timeout_id = setTimeout(function() { 
        window.is_scrolling = false; 
    }, 200); // milliseconds
};

jQuery('.first-frame').bind('touchmove', function(event) {
    if (!window.is_scrolling) 
       _gaq.push(['_trackEvent', 'Landing-Page', 'Swipe-Toggle-Color', '0259_2190']);
});
查看更多
登录 后发表回答