Skip to content

Instantly share code, notes, and snippets.

@bruab
Last active July 19, 2016 01:43
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 bruab/c42727283e83cf023d0071bc03906219 to your computer and use it in GitHub Desktop.
Save bruab/c42727283e83cf023d0071bc03906219 to your computer and use it in GitHub Desktop.
Mobile Email Capture as an Optimizely Test
/* _optimizely_evaluate=force */
window['optimizely'] = window['optimizely'] || [];
// Define experiment object
var _ = $.exp23 = {
INVALID_EMAIL_MESSAGE: 'Please enter your email address',
ENDPOINT: 'https://crometrics.com/custom/googleSheets/api/wrapper',
SUCCESS_MESSAGE: 'Thanks! Let\'s get you a custom quote ...',
DEBUG: false,
};
$('html').addClass('exp23');
/*
** FUNCTIONS THAT RUN ON HOME PAGE **
*/
// Hide elements, insert form, add handlers
_.doHomePage = function() {
// Set timeout if #hero-section is not available yet
if (!$('#hero-section').length) return setTimeout(_.doHomePage, 50);
// Hide CTA and add form
$('#cta-id').css('display', 'none').after('<%- files.form %>');
// Remove placeholder text on input focus
$('#cro-email-input').focus(function() {$(this).attr('placeholder', '');});
// Add handler for form submit
$('#cro-email-form').submit(_.handleFormSubmit);
};
// Display spinner, validate email, ajax-submit form in background,
// display errors or success message; navigate to subpage
_.handleFormSubmit = function(event) {
// Get email value
var email = $('#cro-email-input').val();
if (_.isValidEmail(email)) {
// Trigger custom event
window.optimizely.push(['trackEvent', 'homePageEmailSubmitters']);
// Start 'waiting' animation
_.doWaiting();
// Set cookie
document.cookie = 'croemail=' + email + ';path=/';
// Submit email address
_.ajaxSubmitForm(email);
// Navigate to subpage, but wait for custom goal submission
window.jQuery(document).ajaxStop(_.navigateToSubpage);
} else {
// Display error message
_.showMessage(_.INVALID_EMAIL_MESSAGE);
}
// Don't submit form
return false;
};
// Return a boolean
_.isValidEmail = function(email) {
var emailRegex = /^[a-zA-Z0-9|.|_|\-|\+]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
return emailRegex.test(email);
};
// Display a 'waiting' animation
_.doWaiting = function() {
// Disable input
var $input = $('#cro-email-input');
$input.prop('disabled', true);
// Reduce opacity on input
$input.css('opacity', '0.6');
// Reduce opacity on submit button
var $button = $('#cro-email-form input[type="submit"]');
$button.css('opacity', '0.6');
// Display ellipsis animation on submit button
var count = 0;
setInterval(function(){
var dots = new Array((count % 3)+1).join('•');
$button.attr('value', '•' + dots);
count++;
}, 1000);
};
// Submit email address to Google Sheets API wrapper endpoint
_.ajaxSubmitForm = function(email) {
window.jQuery.ajax({
type: 'POST',
url: _.ENDPOINT,
contentType: 'application/json',
data: JSON.stringify({'Email': email}),
success: function (result) {
if (_.DEBUG) console.log('Success! ', result);
},
error: function (error) {
if (_.DEBUG) console.log('Error! ', error);
}
});
};
_.showMessage = function(message) {
// Display message
$('.cro-message').html(message);
// Remove message on keyup
$('#cro-email-input').bind('keyup', _.clearErrorMessage);
};
// Remove error message when user starts typing
// (ignore enter key)
_.clearErrorMessage = function(event) {
// If user hit the enter key, do nothing
if (event.which === 13) return;
$('.cro-message').html('');
};
_.navigateToSubpage = function() {
window.location.href = '/subpage';
};
/*
** FUNCTION THAT RUNS ON SUBPAGE **
*/
// Pre-fill email field from cookie
_.doSubpage = function() {
// Set timeout if window.jQuery and '#email' not present
if (!window.jQuery) return setTimeout(_.doSubpage, 50);
var $emailField = window.jQuery('#email');
if (!$emailField.length) return setTimeout(_.doSubpage, 50);
var email = '';
// Check for cookie with email address
var cookies = document.cookie.split(';');
for (var i=0; i<cookies.length; i++) {
if (cookies[i].indexOf('croemail') !== -1) {
var splitCookie = cookies[i].split('=');
email = splitCookie[1];
}
}
// Prefill email address
$emailField.val(email).change();
};
/* Execution begins here */
// Test runs on two paths; get URL and execute appropriate function
var pathname = location.pathname;
if (pathname.indexOf('/subpage') !== -1) {
// Get email from cookie and prefill on Subpage
_.doSubpage();
} else {
// On Home Page
// Insert Email form once #hero-section is on the page
_.doHomePage();
}
/* _optimizely_evaluate=safe */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment