Skip to content

Instantly share code, notes, and snippets.

@Nils-van-Kleef
Last active May 25, 2016 07:13
Show Gist options
  • Save Nils-van-Kleef/89b3146d2bba9dbd6c17 to your computer and use it in GitHub Desktop.
Save Nils-van-Kleef/89b3146d2bba9dbd6c17 to your computer and use it in GitHub Desktop.
Custom click goal event that doesn't fire when visitors scroll on mobile/tablet devices
/**
* OPTIMIZELY CUSTOM CLICK EVENTS FRAMEWORK
* customClickEvent.js
* Version 1.0
*
* @install: You can add the following code to your Experiment JavaScript or Project JavaScript
* Replace the SELECTOR with the jQuery selectors of the element(s) you're looking to track
* Replace CUSTOMEVENTGOAL with the name of your custom event goal (eventName)
*
* @explanation: This code fires a custom event goal for Optimizely. For mobile visitors, it
doesn't fire an event goal when a visitor touches the element to scroll the page.
*
* Explanation of added functionality for mobile visitors:
* On touchstart (when somebody touches the element on your page), this will delegate a touchmove (someone
scrolling the page) and touchend (stopping the touch) function to this element.
* When a touchend happens, the event is fired.
* When a touchmove happens, the touchend is undelegate'd (so the touchend will be prevented from firing the
tracking call).
*
* The caveats are:
* This won't work if you have other delegates on this element, if they work with touchmove or touchend,
since these are undelegate'd (removed) with this function.
* You'll have to add this to Experiment JavaScript in all experiments you'd like to use this. You can also
put this code in your Project JavaScript, but then the previous caveat applies to all your webpages with
this project's snippet.
*/
/* _optimizely_evaluate=force */
$(document).ready(function() {
var selector = "SELECTOR";
var customEventName = "CUSTOMEVENTGOAL";
cancelCustomEventTracking = function() {
$(document).undelegate(selector, "touchmove touchend");
};
startCustomEventTracking = function() {
$(document).delegate(selector, "touchmove", function() {
console.log('optimizely tracked event - touchmove');
cancelCustomEventTracking();
});
$(document).delegate(selector, "touchend", function() {
console.log('optimizely tracked event - touchend');
window.optimizely.push(["trackEvent", customEventName]);
});
};
$(document).delegate(selector, "mousedown touchstart", function() {
cancelCustomEventTracking();
startCustomEventTracking();
console.log('optimizely tracked event - touchstart');
});
});
/* _optimizely_evaluate=safe */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment