Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reveal Modal with cookie to display only once

I'm using the (Reveal Modal) and loading it on page by using this code:

$(document).ready(function() {
    $('#myModal').reveal();
});

How can I modify this, I believe using cookies (is there another way?), so that it will only pop one time for a user over the course of lets say 1 week?

like image 382
callmedpit Avatar asked Nov 12 '12 22:11

callmedpit


3 Answers

Use the jquery-cookie plugin by carhartl.

Check for cookie before showing the modal. If it's present, don't display it. If it's not, store a new cookie and display modal.

$(document).ready(function() {
    if ($.cookie('modal_shown') == null) {
        $.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
        $('#myModal').reveal();
    }
});
like image 133
mreq Avatar answered Oct 31 '22 12:10

mreq


Inspired on the code of mreq I created an auto-load using Foundation 5 that appears only after 3 seconds:

$(document).ready(function() {
  if ($.cookie('modal_shown') == null) {
      $.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
      setTimeout(function(){
         $("#myModal").foundation('reveal', 'open');
      }, 3000);
   }
});

Is the same code, but with 3s delay. :)

like image 33
starkbr Avatar answered Oct 31 '22 12:10

starkbr


I had a similar scenario, to only display a jquery modal with dependency on the current day of the week. I utilized the dateJS plugin along with the jquery cookie plugin.

Here is my code:

$(document).ready(function () {
/* We first check if the cookie is equal to null (doesn't exist), if so, we set the cookie to the current site path */
    if($.cookie('modal') == null){
        // Set the cookie
        $.cookie('modal', 'yes', { path: '/' });

        /* Now that the cookie is set once, load the specials */
        // Load Monday's Specials
        if( Date.today().is().monday() ){
            $('#myModal-Monday').reveal();
        }
        // Load Tuesday's Specials
        else if ( Date.today().is().tuesday() ){
            $('#myModal-Tuesday').reveal();
        }
        else if( Date.today().is().wednesday() ){
            $('#myModal-Wednesday').reveal();
        }
        else if( Date.today().is().thursday() ){
            $('#myModal-Thursday').reveal();
        }
        else if( Date.today().is().friday() ){
            $('#myModal-Friday').reveal();
        }
        else if( Date.today().is().sunday() ){
            $('#myModal-Sunday').reveal();
        }
    }
    // The cookie will delete when the browser-closes. Thus only displaying once on the site until the browser is closed
});

So this way the modal is only displayed once during the users browser session and re-displayed only when the user closes/re-opens the browser.

Any feedback on how to optimize would be great!

like image 35
n3my Avatar answered Oct 31 '22 10:10

n3my