I have a multiple modal that loads on my home page. If the user accidentally closes the modal while he is in modal#2, for example, I want the modal to be displayed again where it left off in 12 hours, for example.
I understand this could be done with cookies or maybe localstorage, but I’m new to js and don’t have any idea how to achieve this requirement. I appreciate any help, thanks.
This is the code I have at the moment
const openModal1 = () => {
window.location.href = "#openModal1";
}
const openModal2 = () => {
window.location.href = "#openModal2";
}
const openModal3 = () => {
window.location.href = "#openModal3";
}
window.location.href = "#openModal1";
function start() {
openModal2();
}
const btn_next = () => {;
openModal3();
}
.modalDialog {
position: fixed;
font-family: 'Poppins', sans-serif;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
z-index: 99999;
opacity: 0;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
pointer-events: none;
}
.modalDialog:target {
opacity: 1;
pointer-events: auto;
}
.modalDialog>div {
width: 500px;
position: relative;
margin: 10% auto;
padding: 26px;
border-radius: 2em;
background: #fff;
}
<div id="openModal1" class="modalDialog" data-modalorder="1">
<div>
<a href="#close" title="Close">X</a>
<h1>Content modal 1</h1>
<input type="button" onclick="start()" value="Start">
</div>
</div>
<div id="openModal2" class="modalDialog" data-modalorder="2">
<div>
<a href="#close" title="Close">X</a>
<h1>Content modal 2</h1>
<input type="button" onclick="btn_next()" value="Next">
</div>
</div>
<div id="openModal3" class="modalDialog" data-modalorder="3">
<div>
<a href="#close" title="Close">X</a>
<h1>Content modal 3</h1>
<input type="button" onclick="" value="Next">
</div>
</div>
2
Answers
One method is to listen for
hashchange
event and storelocation.hash
inlocalStorage
or cookies.Here is an example with
localStorage
https://jsfiddle.net/jxy7oznm/
I would advise against inline event handlers (
onclick=...
). It is generally not a good idea.You need something to save the state of your modal windows, and when you want to display the saved state after a certain time also the last time a modal was closed. I think
localStorage
will be suitable for that.The snippet demonstrates how you can use event delegation to handle the clicks. It uses data-attributes to identify what the handler should execute.
In stackblitz snippets
localStorage
is not supported. So I created a small Stackblitz project to demonstrate the use oflocalStorage
. In that project a closed modal re-opens after 15 seconds.