I\'ve developed a couple of alert boxes that display on all site pages.
The user is able to close each box separately:
Following on @Loading.. answer:
the alert boxes always re-appear briefly on reload before disappearing. Any ideas?
Why is this?
The functions inside $(document).ready()
will execute until the entire DOM is loaded. That's why the alerts are rendered, then as soon as the function runs, it hides them.
Solution:
You can initially hide your alerts with a class just to take advantage that the browser won't render the content until the CSSOM has been built.
The class we are using is just setting the property display: none;
.
.hidden {
display: none;
}
This will of course cause redraw in the browser. (see notes)
Your logic is already showing the alert with
if (localStorage.getItem('desiredTime') >= currentTime) {
$('#alert-box-news').hide();
} else {
$('#alert-box-news').show();
}
Because using .show()
will add an inline-style display: block;
it will have a higher specificity than the .hidden
class, showing the alert.
jsFiddle
Notes:
display: none;
will push the content below the alert up or
down. You can use other methods if you like, like visibility: hidden;
or transform
which is not in the scope of this answer.
An illustration will be presented below doing the following steps:
localStorage
function, setting the desiredTime
key.Finally, just to check that the key is indeed being set, we go to:
DevTools (F12) -> Application Tab -> Local Storage -> jsFiddle shell.
Run is hit one more time, after the countdown has finished, showing the alert again.
Illustration:
We might need further details to solve the issue with this approach if it is not working live.
It possible to that with sessionStorage
of javascript.
For exemple :
Storage the current date ( var currentDate
) and date after one minute (var afterOneMinute
)in sessionStorage.
Each click on a button or reload page, change current date and compare them with afterOneMinute
variable and after hide or show box
html File
<head>
<script src="jquery.js"></script>
</head>
<body>
<button onclick="hideOneMinute()">Hide box while 1 minute </button>
<div id="box" style="border: 1px solid red; display: inherit">
<h2>Box</h2>
hello
</div>
<div id="messageBox"></div>
</body>
JS
<script>
var currentDate, afterOneMinute;
function addDate(){
var current = new Date();
// Converts current date in seconds
currentDate = current.getHours()*3600+current.getMinutes()*60+current.getSeconds();
// Current date + 1 minute
afterOneMinute = currentDate + 1*60;
}
addDate();
console.log(currentDate);
// verify sessionStorage when page is reloaded ;
if(typeof(Storage) !== "undefined") {
if(sessionStorage.currentDate){
addDate();
sessionStorage.currentDate = currentDate;
if(Number(sessionStorage.currentDate) < Number(sessionStorage.afterOneMinute))
{
$('#box').hide();
console.log('hide');
}
else{
sessionStorage.clear();
console.log('show');
$('#box').show();
}
}
}
function hideOneMinute() {
if(typeof(Storage) !== "undefined") {
if(sessionStorage.currentDate){
addDate();
sessionStorage.currentDate = currentDate;
if(Number(sessionStorage.currentDate) < Number(sessionStorage.afterOneMinute))
{
$('#box').hide();
}
else{
sessionStorage.clear();
console.log('show');
$('#box').show();
}
}else{
addDate();
sessionStorage.currentDate = currentDate;
sessionStorage.afterOneMinute = afterOneMinute;
console.log('hide');
$('#box').hide();
}
document.getElementById("messageBox").innerHTML = "Box will be shown at " + sessionStorage.afterOneMinute;
} else {
document.getElementById("messageBox").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>
My concrete and lendi process I suggesting you maintain back end database(like sql , mysql etc.) table for that can simple hold user_id, alert box display or not this type of 2 columns are create into that table.
1) If your user is registered user are used visit your site using user id or detail you can manage that alert box.
2) If user is not registered that time use MAC Id of visitor.
Use localStorage()
.
Local storage is per origin (per domain and protocol)
localStorage
as localStorage.setItem('desiredTime', time)
localStorage.getItem('desiredTime')
, based on that show/hide
jQuery
$(document).ready(function(){
//Get current time
var currentTime = new Date().getTime();
//Add hours function
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
//Get time after 24 hours
var after24 = new Date().addHours(10).getTime();
//Hide div click
$('.hide24').click(function(){
//Hide div
$(this).hide();
//Set desired time till you want to hide that div
localStorage.setItem('desiredTime', after24);
});
//If desired time >= currentTime, based on that HIDE / SHOW
if(localStorage.getItem('desiredTime') >= currentTime)
{
$('.hide24').hide();
}
else
{
$('.hide24').show();
}
});
HTML
<div>DIV-1</div>
<div class='hide24'>DIV-2</div>
Things to note
$.cookie
as well, but that's an older approach now.<div>
with class hide24
will be hidden only.localStorage
, you should have HTML5 browsers.Web Storage HTML5
Hope this helps.
Try this solution jsfiddle and read comments regarding storage path. If you are working on sub domain
then you have to specify domain in cookie written like in setCookie()
comments. if you are working on localhost
then the cookie-domain must be set to "" or NULL or FALSE instead of "localhost". For domain reference you can study this stackoverflow question
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 + ";path=/";
// document.cookie = cname + "=" + cvalue + ";" + expires + ";domain=.example.com;path=/"; if you are trying in any sub-domain
}
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 "";
}
$(document).ready(function() {
if(getCookie('news')==1) { //check if cookie news exist if exist then hide.
$("#alert-box-news").hide();
}
if(getCookie('maintenance')==1) { //check if cookie maintenance exist if exist then hide.
$("#alert-box-maintenance").hide();
}
$("#close-alert-box-news").click(function() {
setCookie('news',1,1); // set cookie news to 1 for 1 day = 24 hours here setCookie(key,value,number of cookie expiration day)
$("#alert-box-news").hide(800);
});
$("#close-alert-box-maintenance").click(function() {
setCookie('maintenance',1,1); // set cookie maintenance to 1 for 1 day = 24 hours here setCookie(key,value,number of cookie expiration day)
$("#alert-box-maintenance").hide(800);
});
});
it will not work in stackoverflow. you can test in demo link
Demo
$(document).ready(function() {
checkCookie("alertDisplayed")
$("#close-alert-box-news").click(function() {
setCookie("alertDisplayed", 'yes', 1);
$(".alert-box").hide(800);
});
$("#close-alert-box-maintenance").click(function() {
setCookie("alertDisplayed", 'yes', 1);
$(".alert-box").hide(800);
});
});
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 + ";path=/";
}
function checkCookie(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) {
$(".alert-box").hide();
}
}
return;
}
.alert-box {
width: 50vw;
position: relative;
margin: 20px auto;
border: 1px solid black;
}
.alert-box-close {
position: absolute;
top: -12px;
right: -12px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<article class="alert-box" id="alert-box-news">
<h1>News Alerts</h1>
<p>text text text text text text text text text text text text text text</p>
<a class="alert-box-close" id="close-alert-box-news">
<img src="http://i.imgur.com/czf8yas.png" height="25" width="25" alt="">
</a>
</article>
<article class="alert-box" id="alert-box-maintenance">
<h1>Site Maintenance</h1>
<p>text text text text text text text text text text text text text text</p>
<a class="alert-box-close" id="close-alert-box-maintenance">
<img src="http://i.imgur.com/czf8yas.png" height="25" width="25" alt="">
</a>
</article>