Record Javascript session using cookie and button

Asked

Viewed 810 times

6

I set up a banner, where I need that when the user enters the site and clicks on the GOT IT button it disappears and when the user re-enters the site or loads another link no longer appears. Disappear I managed, but record the user with cookie not, I found an example (below) but did not understand the implementation!!!

Note: Remembering that never expires

COOKIE

// Create a cookie
$.cookie('the_cookie', 'the_value');

// Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });

// Read a cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null

// EDIT
// Attaching to a button click (jQuery 1.7+) and set cookie
$("#idOfYourButton").on("click", function () {
$.cookie('the_cookie', 'the_value', { expires: 7 });
 });

// Attaching to a button click (jQuery < 1.7) and set cookie
$("#idOfYourButton").click(function () {
    $.cookie('the_cookie', 'the_value', { expires: 7 });
});

HTML

<div class="gotit">
    <div>
        <p>We use cookies in order to improve your browsing experience on sugarcane.org, not to collect personal information. By continuing to use the site, you agree that it is OK. <a href="https://sugarcane.org/privacy-policy">Read about our privacy policy.</a></p>
        <a href="#" title="GOT IT">GOT IT</a>
    </div>
</div>

JAVASCRIPT

<script>
$(document).ready(function(){
  $(".gotit A").click(function(){
    $(".gotit").fadeToggle("slow");
  });
});
</script>
  • Do you want a cookie with an expiration date? If so, how long?

  • jQuery Cookie plugin is not missing?

  • @Leocaracciolo I believe so, but load plugin for something so simple that can be done in pure JS I find unnecessary :D

3 answers

5

You can use localStorage which is a type of cookie and set for how many hours the banner will not display when clicking the link to close it.

You need to hide the banner in the CSS, as it will be displayed (or not) when checking the cookie:

.gotit{
   display: none;
}

And the Javascript code:

$(document).ready(function(){

   // atribui o LS a uma vaviável
   var cookie = localStorage.getItem("banner");

   // verifica o cookie
   criaCookie();

   $(".gotit A").click(function(){
      $(".gotit").fadeToggle("slow");
      criaCookie(true);
   });

   function criaCookie(a){
      // pega a data atual
      var data = new Date();

      // variável para guardar a data atual
      var data_atual = data.valueOf();

      // adiciona 168 horas (7 dias) à data atual
      var data_pos = data.setHours(data.getHours()+168);

      if(a){
         // cria/redefine o LS com a data +168 horas
         localStorage.setItem("banner", data_pos);
      }else if(cookie < data_atual){
         // verifica se o LS é menor do que a data atual
         // ou se o LS for inexistente e mostra o banner
         $(".gotit").show();

      }

   }

});

If you want a cookie with no time limit

localStorage is infinite by default, i.e., once created, it is only removed if the user removes it from the browser or by the method localStorage.removeItem("banner").

The option below is when you click GOT IT, the banner no longer appear in the browser where the cookie was created:

$(document).ready(function(){

   // atribui o LS a uma vaviável
   var cookie = localStorage.getItem("banner");

   // verifica o cookie
   criaCookie();

   $(".gotit A").click(function(){
      $(".gotit").fadeToggle("slow");
      criaCookie(true);
   });

   function criaCookie(a){

      if(a){
         // cria o LS
         localStorage.setItem("banner", null);
      }else if(!cookie){
         $(".gotit").show();
      }

   }

});
  • I’ll test and see if it works, but just one more question, if the guy Kill the cookies on his machine show up again right? Another thing, there’s infinite time, like until he deletes the cookie and goes back to the page?

  • Yes, if it deletes it will appear again. It can be infinite yes. By the way, the localStorage is infinite by default, but you can put a time, as I did in the answer.

  • cool, so if I leave there empty is infinite?

  • It worked, but only one problem has to be display:flex and not block tried to put . css('display', 'flex') along with the show line but it didn’t work

  • Would be without the show: $(".gotit").css('display', 'flex') ;. O . show() is display block.

  • vlw was now already up on your post

  • Blz. Now you can mark in one of the answers that solved the question.

Show 2 more comments

3

No jquery cookie plugin

$(document).ready(function(){

  if (document.cookie.indexOf("the_cookie3=") <=0) {
      $(".gotit").css('display', 'flex') ;
      //$('#gotit').show();
  }

  $(".gotit A").click(function(){
      $(".gotit").fadeToggle("slow");
    
        if (document.cookie.indexOf("the_cookie3=") <= 0) {
           alert("O cookie não existe vou criar");

           var date = new Date();
                
          //expira em 7 dias
          //date.setTime(date.getTime()+(7*24*60*60*1000));
                
          //expira em 30 segundos para usar como teste
          date.setTime(date.getTime()+(30*1000));
                
          var expires = "; expires="+date.toGMTString();
          document.cookie = "the_cookie3=the_value"+expires+"; path=/"; 
    
         }
  });
});

HTML put a div

<div class="gotit" style="display:none">
  • Only check was missing when opening the page, whether or not to show the banner.

  • I’m going to give up on your post tb pq worked but just missed what Sam said there and the infinite time

  • @Sam, right, but has trouble checking if the cookie is valid?

  • humm... I have no experience with this type of cookie :/

  • Hey, @Sam, I don’t understand where the banner fits, there’s no banner anywhere. But I think the answer now meets what you said in the first comment

  • It is still half medo this code rs... if you already have a class, why put an id in the div? And the banner will appear only to be hidden later? :?/

  • @Sam, see if it’s still a little meow or just a little bark :)

  • Now it’s cool. Just this one $('#gotit').show(); that has no reason to exist. But it became legal.

  • @Sam forgetfulness

Show 4 more comments

-1

Maybe this will help you.

$(document).ready(function () {
$("a[href^='#']").click(function(){ 
    $.cookie("block", "none",{ expires: 9999999 });
    $(".gotit").css("display", "none");   
}); 
var none = $.cookie("block");
$(".gotit").css("display", none);  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

<div class="gotit">
<div>
    <p>We use cookies in order to improve your browsing experience on sugarcane.org, not to collect personal information. By continuing to use the site, you agree that it is OK. <a href="https://sugarcane.org/privacy-policy">Read about our privacy policy.</a></p>
    <a href="#" title="GOT IT">GOT IT</a>
</div>
</div>

  • You can replace the following snippet $(".gotit"). css("display", "None"); which is inside the CLICK, by $(".gotit"). fadeOut(100); to fade slowly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.