JSFiddle - React, Tailwind, and code Playground
by Terry Mun
HTML
<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="https://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="https://i.imgur.com/czf8yas.png" height="25" width="25" alt="">
</a>
</article>
<button id="clear-localstorage">Clear local storage (for testing)</button>
CSS
.alert-box {
display: none;
width: 50vw;
position: relative;
margin: 20px auto;
border: 1px solid black;
}
.alert-box-close {
position: absolute;
top: -12px;
right: -12px;
cursor: pointer;
}
JavaScript
$(function() {
// Check for localStorage
if (typeof window.localStorage !== typeof undefined) {
// Loop through all alert boxes
$('.alert-box').each(function() {
var $t = $(this),
key = $t.attr('id');
// If key exists and it has not expired
if (window.localStorage.getItem(key)) {
var json = JSON.parse(window.localStorage.getItem(key));
if (json.hide && json.timestamp < Date.now() + 1000 * 60 * 60 * 24) {
$t.hide();
} else {
$t.show();
}
} else {
$t.show();
}
});
}
// Bind click events to alert boxes
$('.alert-box a.alert-box-close').click(function() {
var $alertBox = $(this).closest('.alert-box');
// Hide box
$alertBox.hide(800);
// Store option in localStorage, using the box's ID as key
if (typeof window.localStorage !== typeof undefined) {
window.localStorage.setItem($alertBox.attr('id'), JSON.stringify({
hide: true,
timestamp: Date.now()
}));
}
});
// For demo purposes only, clear localStorage to ease testing
$('#clear-localstorage').click(function() {
window.localStorage.clear();
});
});