Показывать Modal с cookie для отображения только один раз.
Я использую (Reveal Modal) и загружаю его на страницу с помощью этого кода:
$(document).ready(function() {
$('#myModal').reveal();
});
Как я могу изменить это, я считаю, что использование файлов cookie (есть ли другой способ?), так что он будет только один раз появляться для пользователя в течение времени, скажем, 1 неделю?
Ответы
Ответ 1
Используйте плагин jquery-cookie по carhartl.
Проверяйте файл cookie перед показом модальности. Если он присутствует, не показывайте его. Если это не так, сохраните новый файл cookie и покажите модальный.
$(document).ready(function() {
if ($.cookie('modal_shown') == null) {
$.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
$('#myModal').reveal();
}
});
Ответ 2
Вдохновленный кодом mreq
, я создал автозагрузку, используя Foundation 5, которая появляется только через 3 секунды:
$(document).ready(function() {
if ($.cookie('modal_shown') == null) {
$.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
setTimeout(function(){
$("#myModal").foundation('reveal', 'open');
}, 3000);
}
});
Это тот же код, но с задержкой 3 с.:)
Ответ 3
У меня был похожий сценарий, чтобы отображать только мода jquery с зависимостью от текущего дня недели. Я использовал плагин dateJS вместе с плагином jQuery cookie.
Вот мой код:
$(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 Specials
if( Date.today().is().monday() ){
$('#myModal-Monday').reveal();
}
// Load Tuesday 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
});
Таким образом, модальный отображается только один раз во время сеанса браузера пользователей и повторно отображается только тогда, когда пользователь закрывает/повторно открывает браузер.
Любая обратная связь о том, как оптимизировать, будет отличной!
Ответ 4
Так я сделал это с помощью jQuery и простых Js. Здесь хорошо объяснено: http://www.w3schools.com/js/js_cookies.asp
// Set the Cookie
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
// Get the Cookie
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) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Check if Cookie exists
function checkCookie() {
// Get the cookie called "visited"
var visited = getCookie("visited");
// If it exists, print the Cookie to the Console
if (visited == "true") {
console.log(document.cookie);
}
else {
// If not, add the class 'is-visible' to my modal called '.mhc-intro-modal'
// and create a the cookie "visited=true" expiring in 15 days.
$('.mhc-intro-modal').addClass('is-visible');
$('body').addClass('hide-overflow');
setCookie("visited", "true", 15);
}
}
// When document is ready check for the cookie
$(document).ready(function() {
checkCookie();
});
// Close the modal
$('.mhc-intro-modal').on('click', function(event) {
if ( $(event.target).is('.mhc-intro-modal-close') || $(event.target).is('.mhc-intro-modal') ) {
event.preventDefault();
$(this).removeClass('is-visible');
$('body').removeClass('hide-overflow');
}
});
CSS
body {
background-color: #fbfbfb;
&.hide-overflow {
overflow: hidden;
}
}
.mhc-intro-modal {
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
background-color: rgba(21, 21, 21, 0.55);
opacity: 0;
visibility: hidden;
transition: opacity 0.3s 0s, visibility 0s 0.3s;
&.is-visible {
opacity: 1;
visibility: visible;
z-index: 11;
transition: opacity 0.3s 0s, visibility 0s 0s;
}
}
HTML
<div class="mhc-modal mhc-intro-modal" role="alert">
<div class="mhc-modal-inner">
<div class="mhc-modal-info-container">
<a href="#0" class="mhc-intro-modal-close">Close</a>
<div class="mhc-copy-container" style="background-image: url('your-image-path.jpg');">
<h3 class="mhc-title">The Title</h3>
<p class="mhc-description">The description bla bla bla</p>
</div>
</div>
</div>
</div>