I have a website that displays a model on index load. Currently it loads every single time you go to the index page. It gets very annoying to the users of the website. I was wondering if I can only display it once per hour per user? The website is located at wikiraces.com
JavaScript
x
62
62
1
<!-- MODAL FOR NEWS-->
2
<div id="div1" class="modal">
3
4
<!-- Modal content -->
5
<div class="modal-content">
6
<span class="close">×</span>
7
</div>
8
<!-- Modal content -->
9
<div class="modal-content">
10
<div class="modal-header">
11
<span class="close">×</span>
12
<h2>New Features/Updates</h2>
13
</div>
14
<div class="modal-body">
15
<h4> <p>The Fewest Clicks Game is Back!</p> </h4>
16
<p>
17
It was down for maintanece for 14 hours but finally it is back
18
</p>
19
20
<h4> The Multiplayer host random page is here! </h4>
21
<p>
22
You can now play multiplayer without the hassle of chosing your own start!
23
<br>
24
<br>
25
<a href="/html/about.html"> <b> Report bugs </b></a>
26
27
</p>
28
</div>
29
<div class="modal-footer">
30
<h5> Enjoy, and remember to share this website with your friends! </h5>
31
</div>
32
</div>
33
</div>
34
35
</div>
36
37
<script>
38
// Get the modal
39
var modal = document.getElementById("div1");
40
41
// Get the <span> element that closes the modal
42
var spanTimed = document.getElementsByClassName("close")[0];
43
44
// When the user clicks on the button, open the modal
45
window.onload = function() {
46
modal.style.display = "block";
47
}
48
49
// When the user clicks on <span> (x), close the modal
50
spanTimed.onclick = function() {
51
modal.style.display = "none";
52
}
53
54
// When the user clicks anywhere outside of the modal, close it
55
window.onclick = function(event) {
56
if (event.target == modal) {
57
modal.style.display = "none";
58
}
59
}
60
61
</script>
62
Advertisement
Answer
We can store the last time the modal was opened in localStorage
and everytime the user visits the site, we can check the difference between the time stored and the current time. If the time spend is greater than one hour, then show the modal.
JavaScript
1
15
15
1
window.addEventListener('load', () => {
2
let time = localStorage.getItem('time');
3
if ( time === null ) {
4
localStorage.setItem('time', new Date());
5
modal.style.display = "block";
6
return;
7
}
8
9
let current = new Date();
10
if ( current - time >= 60 * 60 * 1000 ) {
11
modal.style.display = "block";
12
}
13
14
})
15