I am trying to build a reminder for my website. I am using the bootstrap modal to show the messages. When the user closes the modal, I don’t want to show the modal to that user for the day. The next day the user will see the message.
First I plan to use localStorage but it does not have any expiration feature. So cookie is the best option. I set the cookie for one day and if the cookie exists the modal won’t show.
if ( cookie_not_exists ){
$('#info-modal').modal('show');
}
$('#info-modal').on('hide.bs.modal', function(){
// Set the cookie.
});
My question is, how do I set and get the cookie with javascript?
You can write your getCookie and setCookie function.
function setCookie(name, value, timeinSec) {
var expires = "";
if (timeinSec) {
var date = new Date();
date.setTime(date.getTime() + (timeinSec*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function deleteCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}