javascriptjquerymagnific-popupjquery-cookie

Load Magnific Popup once every 15 days for new user


I have a newsletter sign up form that I would like to load (popup) only one time every 15 days, otherwise it might get a bit annoying. I am currently using this jquery code to load the popup form when the page loads.

<div id="test-popup" class="white-popup mfp-hide">
Popup Form
</div>

<script>
jQuery(window).load(function(){
jQuery.magnificPopup.open({
items: {src: '#test-popup'},type: 'inline'}, 0);
});
</script>

This works fine when loading the form every time you access the page but I would like to limit this so new users see it once every 15 days. Not sure if the 15 days is best practice just something I came up with?


Solution

  • You can use localStorage to do this.

    $(window).on('load', function() {
      var now, lastDatePopupShowed;
      now = new Date();
    
      if (localStorage.getItem('lastDatePopupShowed') !== null) {
        lastDatePopupShowed = new Date(parseInt(localStorage.getItem('lastDatePopupShowed')));
      }
    
      if (((now - lastDatePopupShowed) >= (15 * 86400000)) || !lastDatePopupShowed) {
        $.magnificPopup.open({
          items: { src: '#test-popup' },
          type: 'inline'
        }, 0);
    
        localStorage.setItem('lastDatePopupShowed', now);
      }
    });
    
    <div id="test-popup" class="white-popup mfp-hide">
      Popup Form
    </div>
    

    You can see a working example here: http://codepen.io/caio/pen/Qwxarw