I have a site that shows a modal window when the page is loaded. I want this to only be shown to visitors the first time they come to the site however.
I have set JavaScript to add a cookie on page load but I want that cookie to be read (if present) and hide the modal (if cookie present).
I have the following Javascript (no jQuery):
<script language="JavaScript">
if (document.cookie.indexOf('visited=true') == -1) {
var oneyear = 1000*60*60*24*365;
var expires = new Date((new Date()).valueOf() + oneyear);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
//Check if cookie is present and hide myModal DIV
if (document.cookie.indexOf('visited=true') >= 0) {
document.getElementById('myModal').modal.style.display = "none";
}
</script>
My Html is:
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="content">
<p>Text to be shown here</p>
<button id="closeBtn">Close</button>
</div>
</div>
</div>
The cookie is being set on the page load, but it's not being read on second page load and hiding #myModal
** Update**
I have updated the above code, following the answers below but now I have got an error in the Console:
Uncaught TypeError: Cannot read property 'style' of null
Modify this.You are checking string ( visited=true=
) wrong. Set it to visited=true
or visited=
is the best option as per me
if (document.cookie.indexOf('visited=') >= 0) {
document.getElementById('myModal').modal.style.display = "none";
}
You are checking the wrong string :
if (document.cookie.indexOf('visited=true=') >= 0) {
should be
if (document.cookie.indexOf('visited=true') >= 0) {
Could it be the .modal. that needs to be removed? Ie change
if (document.cookie.indexOf('visited=') >= 0) {
document.getElementById('myModal').modal.style.display = "none";
}
to:
if (document.cookie.indexOf('visited=') >= 0) {
document.getElementById('myModal').style.display = "none";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.