tara-m of Underwaterpistol Code Snippets
1/30/2019 - 2:49 PM

Exit Intent

Step 1: 
Open theme.liquid and add this snippet in the head directly underneath jQuery, if jQuery is not in the head move it there.

  {{ 'jquerycookie.js' | asset_url | script_tag }}
  
  <script type="text/javascript">
    var popQueue = [];
  </script>
  
  
Step 2: 
Create an asset called "jquerycookie.js" and add this code:

	/*!
     * jQuery Cookie Plugin v1.4.1
     * https://github.com/carhartl/jquery-cookie
     *
     * Copyright 2006, 2014 Klaus Hartl
     * Released under the MIT license
     */
      
    !function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e("object"==typeof exports?require("jquery"):jQuery)}(function(e){function n(e){return u.raw?e:encodeURIComponent(e)}function o(e){return u.raw?e:decodeURIComponent(e)}function i(e){return n(u.json?JSON.stringify(e):String(e))}function r(e){0===e.indexOf('"')&&(e=e.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return e=decodeURIComponent(e.replace(c," ")),u.json?JSON.parse(e):e}catch(n){}}function t(n,o){var i=u.raw?n:r(n);return e.isFunction(o)?o(i):i}var c=/\+/g,u=e.cookie=function(r,c,a){if(arguments.length>1&&!e.isFunction(c)){if(a=e.extend({},u.defaults,a),"number"==typeof a.expires){var f=a.expires,s=a.expires=new Date;s.setTime(+s+864e5*f)}return document.cookie=[n(r),"=",i(c),a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}for(var d=r?void 0:{},p=document.cookie?document.cookie.split("; "):[],m=0,x=p.length;x>m;m++){var l=p[m].split("="),g=o(l.shift()),k=l.join("=");if(r&&r===g){d=t(k,c);break}r||void 0===(k=t(k))||(d[g]=k)}return d};u.defaults={},e.removeCookie=function(n,o){return void 0===e.cookie(n)?!1:(e.cookie(n,"",e.extend({},o,{expires:-1})),!e.cookie(n))}});

 
Step 3: 
Create a js file and call it "exit-intent.js.liquid" and include it in the bottom of your theme liquid file

/*!
 * CoverPop 2.5.1
 * http://coverpopjs.com
 *
 * Copyright (c) 2015 Tyler Pearson
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */
!function(e){"use strict";var o={coverId:"CoverPop-cover",expires:30,closeClassNoDefault:"CoverPop-close",closeClassDefault:"CoverPop-close-go",openClassDefault:"CoverPop-open",cookieName:"_CoverPop",onPopUpOpen:null,onPopUpClose:null,forceHash:"splash",delayHash:"go",closeOnEscape:!0,delay:0,hideAfter:null},s={},t={hasClass:function(e,o){return new RegExp("(\\s|^)"+o+"(\\s|$)").test(e.className)},addClass:function(e,o){t.hasClass(e,o)||(e.className+=(e.className?" ":"")+o)},removeClass:function(e,o){t.hasClass(e,o)&&(e.className=e.className.replace(new RegExp("(\\s|^)"+o+"(\\s|$)")," ").replace(/^\s+|\s+$/g,""))},addListener:function(e,o,s){e.addEventListener?e.addEventListener(o,s,!1):e.attachEvent&&e.attachEvent("on"+o,s)},removeListener:function(e,o,s){e.removeEventListener?e.removeEventListener(o,s,!1):e.detachEvent&&e.detachEvent("on"+o,s)},isFunction:function(e){var o={};return e&&"[object Function]"===o.toString.call(e)},setCookie:function(e,o){var s=new Date;s.setTime(+s+864e5*o),document.cookie=e+"=true; expires="+s.toGMTString()+"; path=/"},hasCookie:function(e){return-1!==document.cookie.indexOf(e)?!0:!1},hashExists:function(e){return-1!==window.location.hash.indexOf(e)?!0:!1},preventDefault:function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},mergeObj:function(e,o){for(var s in o)e[s]=o[s]}},n=function(s){o.closeOnEscape&&27===s.keyCode&&e.close()},l=function(){if(null!==o.onPopUpOpen){if(!t.isFunction(o.onPopUpOpen))throw new TypeError("CoverPop open callback must be a function.");o.onPopUpOpen.call()}},a=function(){if(null!==o.onPopUpClose){if(!t.isFunction(o.onPopUpClose))throw new TypeError("CoverPop close callback must be a function.");o.onPopUpClose.call()}};e.open=function(){var a,c;if(t.hashExists(o.delayHash))return void t.setCookie(o.cookieName,1);if(t.addClass(s.html,o.openClassDefault),s.closeClassNoDefaultEls.length>0)for(a=0,c=s.closeClassNoDefaultEls.length;c>a;a++)t.addListener(s.closeClassNoDefaultEls[a],"click",function(o){o.target===this&&(t.preventDefault(o),e.close())});if(s.closeClassDefaultEls.length>0)for(a=0,c=s.closeClassDefaultEls.length;c>a;a++)t.addListener(s.closeClassDefaultEls[a],"click",function(o){o.target===this&&e.close()});t.addListener(document,"keyup",n),l()},e.close=function(){t.removeClass(s.html,o.openClassDefault),t.setCookie(o.cookieName,o.expires),t.removeListener(document,"keyup",n),a()},e.init=function(n){navigator.cookieEnabled&&(t.mergeObj(o,n),s={html:document.getElementsByTagName("html")[0],cover:document.getElementById(o.coverId),closeClassDefaultEls:document.querySelectorAll("."+o.closeClassDefault),closeClassNoDefaultEls:document.querySelectorAll("."+o.closeClassNoDefault)},(!t.hasCookie(o.cookieName)||t.hashExists(o.forceHash))&&(0===o.delay?e.open():setTimeout(e.open,o.delay),o.hideAfter&&setTimeout(e.close,o.hideAfter+o.delay)))},e.start=function(o){e.init(o)}}(window.CoverPop=window.CoverPop||{});
(function($){
    function startPopup(){
        {% if settings.enable_persistent_intent %}
            var date = new Date();
            var minutes = {{ settings.ExitIntent_cookie_delay }};
            var expireDelay = date.setTime(date.getTime() + (minutes * 60 * 1000));
        {% endif %}

        CoverPop.start({
            coverId:             'CoverPop-cover',       // set default cover id
            {% if settings.enable_persistent_intent %}
            expires:             expireDelay,                    // duration (in days) before it pops up again
            {% else %}
            expires:             365,                    // duration (in days) before it pops up again
            {% endif %}
            closeClassNoDefault: 'CoverPop-close',       // close if someone clicks an element with this class and prevent default action
            closeClassDefault:   'CoverPop-close-go',    // close if someone clicks an element with this class and continue default action
            cookieName:          '_exit_intent',         // to change the plugin cookie name
            onPopUpOpen:         function() {},          // on popup open callback function
            onPopUpClose:        function() {
                console.log('Exit Intent Popup closed');
            },                                           // on popup close callback function
            forceHash:           'splash',               // hash to append to url to force display of popup (e.g. http://yourdomain.com/#splash)
            delayHash:           'go',                   // hash to append to url to delay popup for 1 day (e.g. http://yourdomain.com/#go)
            closeOnEscape:       true,                   // close if the user clicks escape
            delay:               0,                      // set an optional delay (in milliseconds) before showing the popup
            hideAfter:           null                    // set an optional time (in milliseconds) to autohide
        });
    }
    $(document).ready( function () {
        var $mcMailForm = $('#mc-embedded-subscribe-form');
        $('#mc-embedded-subscribe.btn').on('click', function(e){
            e.preventDefault();
            register($mcMailForm);
        });
        $('input').on('input', function(){
            $('.no-content').removeClass('error');
        });
        $('.CoverPop-close, #CoverPop-cover').click(function(){
            CoverPop.close();
            console.log('Exit Intent Popup closed - No Signup detected');
        });
        $('.popup-wrapper').on('click', function(e){
            e.stopPropagation();
        });
        function register($mcMailForm) {
            $.ajax({
                type: $mcMailForm.attr('method'),
                url: $mcMailForm.attr('action'),
                data: $mcMailForm.serialize(),
                cache       : false,
                dataType    : 'json',
                contentType: "application/json; charset=utf-8",
                error       : function(err) { console.log('connection error contact hello@WEMAKEWEBSITES.COM') },
                success     : function(data) {
                    if (data.result != "success") {
                        $('.no-content').addClass('error').html(data.msg);
                    } else {
                        $('.mc-field-group').removeClass('error');
                        $('#mc_embed_signup_form').html('<h3>{{ settings.exitIntent-message }}</h3>');
                        $("body").delay(2500).queue(function() {
                            CoverPop.close();
                            console.log('Exit Intent Popup closed with signup - Exit intent diactivated');
                        });
                        $.cookie("_exit_intent", "signedup", { expires: 365 , path: '/' });
                    }
                }
            });
        }
        
        function delayIntent(){

            // Exit intent
            function addEvent(obj, evt, fn) {
                if (obj.addEventListener) {
                    obj.addEventListener(evt, fn, false);
                }
                else if (obj.attachEvent) {
                    obj.attachEvent("on" + evt, fn);
                }
            }
             
            // Exit intent trigger
            addEvent(document, 'mouseout', function(evt) {
                if( popQueue.length == 0 ){
                    if (evt.toElement == null && evt.relatedTarget == null ) {
                        if( ( $.cookie('_exit_intent') != 'true' ) ){
                            console.log('Exit Intent: Mouse has left the area');
                            console.log('No Exit Intent Cookie Found');
                            console.log('Exit Intent Popup Deployed');
                            $.removeCookie('_exit_intent', { path: '/' }); // => true
                            setTimeout( startPopup, 800);
                        } else if( ( $.cookie('_exit_intent') == 'true' ) ){
                            console.log('Exit Intent Closed - No Signup Detected - Exit Intent Delayed');
                        } else if( ( $.cookie('_exit_intent') == 'signedup' ) ){
                            console.log('Exit Intent Cookie Detected - Signup Detected - Exit Intent Deactivated');
                        }
                    };
                } else {
                    console.log('There is another popup open');
                }
            });

            console.log('Exit Intent is Active');
        }

        setTimeout( delayIntent, {{ settings.ExitIntent_popup_delay | times: 1000 }} );
    });
})(jQuery);
 
 
Step 4: 
Copy this scss and put it at the end of you main style file

/* //////// Exit Intent ////////// */
.error_special{
    background: #F8C2C2;
    padding: 10px;
    span{
        font-size: 12px;
        font-weight: normal;
        margin-top: 10px;
        display: inline-block;
        width: 100%;
    }
    .help-error{
        display: inline-block;
        width: 100%;
        text-align: center;
        color: #e3120b;
    }
}
.CoverPop-open,
.CoverPop-open body {
    overflow: hidden;
}
#CoverPop-cover {
    display: none;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9998;
    -webkit-animation: fade-in .25s ease-in;
    -moz-animation-name: fade-in .25s ease-in;
    -ms-animation-name: fade-in .25s ease-in;
    -o-animation-name: fade-in .25s ease-in;
    animation-name: fade-in .25s ease-in;
    background: rgba(0,0,0,0.5);
}

@-webkit-keyframes fade-in {
    0% { opacity: 0; }
    25% { opacity: 0; }
    100% { opacity: 1; }
}

.CoverPop-open #CoverPop-cover {
    display: block;
}
 
 
form{
    label{
        display: inline-block;
        width: 100%;
        margin-bottom: 5px;
    }
    .mc-field-group{
        display: inline-block;
        width: 100%;
        padding: 10px 20px 2px;
        input[type="text"], input[type="email"]{
            width: 100%;
            float: left;
        }
    }
    .indicates-required{
        float: right;
        display: inline-block;
        font-size: 10px;
        color: #BBB;
        text-transform: uppercase;
        padding: 10px;
    }
    label[for="agree"]{
        float: right;
        width: 95%;
        display: inline;
        font-size: 12px;
        margin-top: 3px;
    }
 
    #mc-embedded-subscribe{
        margin: 20px auto;
        outline: none;
        display: block;
        background-color: #79878e;
       color: #fff;
        width: 16%;
        padding: 0.9em;
    }
    .error{
        font-size: 10px;
        color: #e3120b;
        display: inline-block;
        width: 100%;
        margin-bottom: 5px;
        float: left;
    }
}
 
.form-title{
    color: #e3120b;
    text-align: center;
    font-weight:300;
}
input.mce_inline_error{
    border-color: #e3120b!important;
}
div.mce_inline_error{
    color: #e3120b;
    font-size: 10px;
}
.no-content{
    height: 0;
    overflow: hidden;
    display: inline-block;
    width: 100%;
    text-align: center;
    margin-top: 15px;
    &.error {
        height: 30px;
        color: #e3120b;
    }
}
#mc_embed_signup_form{
    background: #f7f7f7;
    display: inline-block;
    padding: 5px;
}

.popup-wrapper{
  position: relative;
  z-index: 9999;
  width: 100%;
  margin: 0 auto;
  max-width: 600px;

  .CoverPop-close{
      color: #79878e;
      display: inline-block;
      width: 100%;
      margin-top: 10px;
      width: 100%;
      text-align: center;
      text-transform: uppercase;
      font-size: 14px;
      font-weight: 500;
  }
}
 
 
Step 5: 
Create a snippet called "exit-intent.liquid" and include it in the bottom of your theme.liquid file 

MAKE SURE TO CHANGE THE FORM ACTION URL IN THE MAILCHIMPURL ASSIGN

{% assign mailchimpURL = settings.exit_intent_form_action %}
{% assign ajaxURL = mailchimpURL | replace: 'post?', 'post-json?' | append: '&c=?' %}
  
<div id="CoverPop-cover" class="splash">
    <div class="CoverPop-content splash-center popup-wrapper">
        <div id="mc_embed_signup_form">
            <form action="{{ ajaxURL }}" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
                <div class="no-content">Please Enter Name and Email</div>
                <div id="mc_embed_signup_scroll">
                    <div class="mc-field-group">                 
                        <h2 class="form-title">{{ settings.popup_form_title }}</h2>
                    </div>
                    <div class="mc-field-group">
                        <label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
                        </label>
                        <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
                    </div>
                    <div class="mc-field-group">
                        <label for="mce-FNAME">First Name <span class="asterisk">*</span></label>
                        <input type="text" value="" name="FNAME" class="required name" id="mce-FNAME">
                    </div>
                    <div class="mc-field-group">
                        <label for="mce-LNAME">Last Name <span class="asterisk">*</span></label>
                        <input type="text" value="" name="LNAME" class="required name" id="mce-LNAME">
                    </div>
                    <div id="mce-responses" class="clear">
                        <div class="response" id="mce-error-response" style="display:none"></div>
                        <div class="response" id="mce-success-response" style="display:none"></div>
                    </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
                    <div style="position: absolute; left: -5000px;"><input type="text" name="b_530aa3e9fbf5498155fb54ea4_b9c475158c" tabindex="-1" value=""></div>
                    <div class="clear">
                        <input type="submit" value="Join" name="subscribe" id="mc-embedded-subscribe" class="btn margin-bottom--large">
                    </div>
                        
                    <a class="CoverPop-close" href="#">No thank you</a>
                </div>
            </form>
            <div class="top-right-exit"><a class="CoverPop-close" href="#"><i class="fa fa-close"></i></a></div>
        </div>
    </div><!--end .splash-center -->
</div>
 
Step 6: Add these theme setting to settings_scheme.json
{
  "name": "Exit Intent",
  "settings": [
    {
      "type": "text",
      "id": "exit_intent_form_action",
      "label": "Mailchimp Form Action URL"
    },
    {
      "type": "text",
      "id": "ExitIntent_popup_delay",
      "label": "Seconds to delay exit intent popup when the page first loads"
    },
    {
      "type": "checkbox",
      "id": "enable_persistent_intent",
      "label": "Do you want the Popup to persist if it is closed without signup?"
    },
    {
      "type": "text",
      "id": "ExitIntent_cookie_delay",
      "label": "Minutes to wait before asking again if a user closes without signing up"
    }
  ]
},