Set Cookie to Show / Hide Div

My first attempt at writing javascript - and so far my efforts are drawing a complete blank.

What I’m aiming to do is present visitors to my website with a ‘Welcome’ message on their First visit.
I’m not asking them to input their name or anything - it’s just a one-off message.
(actually the solution i have below gives me 365 days so they get a reminder every year)

To do this i plan to inspect a cookie when they arrive
If there is no cookie set, i show them the message - and set the cookie.
if the cookie is set then i do nothing.

The message is to be shown as a Div in the webpage - so i need to show/hide that Div depending on the existence or otherwise of the cookie.

I found some javascript (courtesy of Paul_Wilkins) on this very site that came close to what i want to do.
I’ve cannibalised it a bit - not much… but it is returning a complete blank.
Not only doesn’t it show the Div - it doesn’t even set the Cookie.
So pretty much a non-starter so far.

Here’s what I’ve got…

CSS Definition for the div:

#welcome {
	display: none;
	}

#welcome.show {
   	float: left;
	width: 765px; 
	height: 70px; 
	font-size: 15px;
	background-color: #e29206;
    display: block;   }

Javascript To Create and Read a Cookie - placed just before the < /head>

<script type="text/javascript">

function createCookie(name,value,days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";      }

function readCookie(name) {
	var nameEQ = name + "=";
	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,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;        }

</script>

Javascript to access the Cookie - _placed just before < /body>

<script type="text/javascript">

var days = 365;
var welcome = document.getElementById(‘welcome’);
if (readCookie(‘lazycookie’)) {
    welcome.className = '';
} else {
    welcome.className = 'show';
    createCookie(‘lazycookie’, 'yes', days);
}

</script>

As I mentioned - I’m getting no response from the coding and no clue as to where i’m going wrong.
Any advice much appreciated.

1 Like

I’d consider using local storage instead of cookies. See this SO thread as to why.

var hasSeenGreeting = localStorage.getItem("greeting");
if(!hasSeenGreeting){
  document.getElementById("welcome").style.display = "block";
  localStorage.setItem("greeting", "true");
}

By way of a complete example, here’s a demo. The first time you run this, you should see the welcome message displayed. If you run it a second time or more (the Run button is in the top left corner) you won’t see the message.

If you click the Reset Local Storage button, this will clear the key/value pair from local storage, then the next time you run the demo you’ll see the message again.

Here’s the complete code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Local Storage Example</title>
    <style>
      #welcome {
        display: none;
        float: left;
        width: 765px;
        height: 70px;
        font-size: 15px;
        background-color: #e29206;
      }

      button{
        margin-top: 15px;
      }
    </style>
  </head>
  <body>
    <div id="welcome">
      <p>Hello, there!</p>
    </div>

    <button>Reset Local Storage</button>

    <script>
      var hasSeenGreeting = localStorage.getItem("greeting");

      if(!hasSeenGreeting){
        document.getElementById("welcome").style.display = "block";
        localStorage.setItem("greeting", "true");
      }

      document.querySelector("button").addEventListener("click", function(){
        localStorage.removeItem("greeting", "true");
      });
    </script>
  </body>
</html>

HTH

4 Likes

Thanks Pullo - this looks excellent - i’m way passed exhausted now so i’ll pick it up in the (UK) morning.
Thanks for a great reply…

1 Like

That was a great read. Thanks! I’ve been out of the loop with front end for awhile and though I’ve heard about local storage. I never knew its true intention.

1 Like

No worries, let us know how you get on.

Support is also excellent: Can I Use namevalue-storage?. Only Opera Mini doesn’t support this.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.