DevOverflow
DevOverflow

Reputation: 39

Adding a simple Cookie / Local Storage to remember if user has clicked

I have added a cookies notice bar on my site.

I want the site to remember if the user has clicked to exit the notice so that it doesn't come up on every page or when they revisit the page. In other words, I want to make a cookie to remember if the the user has acknowledged it. I want this to be permanent with no expiry (not just a temporary cookie for that browser session).

I am told that LocalStorage is a good option for this, though I don't have any particular grudge against using javascript cookies instead (I don't really know the difference). Any permanent solutions are appreciated, but preferably without having to use a library given that it should be simple.

HTML

  <div class='cookie-notice'>
    We use cookies 
    <div class='exit'>
      X
    </div>
  </div>

jQuery

$('.exit').click(function(){
  $('.cookie-notice').css('display','none');
});

Upvotes: 0

Views: 550

Answers (1)

Duc Nguyen
Duc Nguyen

Reputation: 855

  • Cookies are sent back and forth between the server and client on every HTTP request.

  • Web Storage is for storing information in the client only.

So to set it permanent, you should use the localStorage provided by the Web Storage API.

const isNoticeSeen = window.localStorage['noticeSeen'] === 'true';
if (isNoticeSeen) {
  $('.cookie-notice').css('display','none');
}

$('.exit').click(function(){
    window.localStorage['noticeSeen'] = true;
});

Here's the fiddle link: https://jsfiddle.net/qbe0vLpk/

Upvotes: 1

Related Questions