Twitter Bootstrap Modal and Jquery Cookie Plugin

I’m trying to get the modal only to pop up once per week.

I’m using WordPress, and Roots theme, and have the scripts enqueued and registered correctly.

Read More

My code for the modal is

<div class="modal hide fade modalborder" id="myModal">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <div class="modal-body">
            <h2 class="modalheader">Header Here</h2>
            <p class="modalcoffee">Text here</p>
            <p class="modalcomesin">Text here</p>
        </div>
        <p class="modallearn">Text Here</p>
        <p class="modalready">Are you ready to <span class="modalstart">start</span>?</p>
        <a href="#" class="btn btn-info">Click Here</a>
    </div>
</div>

The current javascript to make this show works perfectly:

<script type="text/javascript">
$(window).load(function(){
    $('#myModal').modal('show');
});
</script>

I know very little about jQuery and javascript for that matter. What would I need to do to make this work with cookies?

Related posts

Leave a Reply

2 comments

  1. First you need to include the JQuery cookie plugin like so:

    <script src="/path/to/jquery.cookie.js"></script>
    

    Then the following code should help you:

    <script type="text/javascript">
    $(function(){
        // If the cookie does not exist
        if ($.cookie('modalshow') === null) 
        {
           // Show the modal
           $('#myModal').modal('show');
           var expiryDate = new Date();
           var hours = 168;
           expiryDate.setTime(expiryDate.getTime() + (hours * 3600 * 1000));
    
           // Create cookie to expire in 168 hours (1 week)
           $.cookie("modalshow", "false", { path: '/', expires: expiryDate });
        }
    });
    </script>
    
  2. same as @mccanff answer but without using external libs

    if (document.cookie.indexOf("modalshow=true") < 0) {
        $('#myModal').modal('show');
        var expiryDate = new Date();
        var hours = 168;
        expiryDate.setTime(expiryDate.getTime() + (hours * 3600 * 1000));
        document.cookie = "modalshow=true; expires=" + expiryDate + "; path=/";
    }