Ad

Simplest Way To Add A Cookie To Bootstrap's Modal?

- 1 answer

I have a modal on my website that pops up when they first visit with terms and conditions. The annoying thing is once they agree to the terms it keeps popping up on refresh.

Is there any simple way of adding a cookie to bootstraps modal so when users visit they only have to agree once?

Is a plugin necessary?

Ad

Answer

You don't need a plugin, just some plain 'ol javascript will do the trick.

First, this sets a cookie when the modal is closed:

$('#myModal').on('hidden.bs.modal', function (e) {
    // set cookie
   document.cookie = "showModalOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
})

Then wherever your code is that opens the modal, check the cookie first, something like this:

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
        }
    return "";
}

// open modal only if cookie is not set
if ( getCookie('showModalOnlyOnce') !== 'true' ) {
    $('#myModal').modal('show');
}
Ad
source: stackoverflow.com
Ad