Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript onclick function with cookies

For example i have a <P>tag contain a class as below

<p class="badge">new</p>

and i do like to add some CSS for the element, when the user .onclick(), so i created a function like below

 $(".badge").click(function(){
    $(".badge").css("display","none");
});

And the question is how may i use cookies to remember that the user had already clicked before, so the css will be added automatically?

like image 786
Anson Aştepta Avatar asked Jul 09 '26 15:07

Anson Aştepta


2 Answers

You're better off using window.localStorage

 $(".badge").click(function(){
    $(".badge").css("display","none");
    localStorage.setItem('btnClicked', true);
 });

And on document load you should check if the user has clicked the button before and act accordingly:

$(document).ready(function (){
    var clicked = localStorage.getItem("btnClicked");
    if(clicked){
       $(".badge").css("display","none");
    }
});
like image 154
dimlucas Avatar answered Jul 12 '26 08:07

dimlucas


You could use the jQuery cookie library:-

Create expiring cookie, 7 days from then:

$.cookie('name', 'value', { expires: 7 }); 

Read cookie:

$.cookie('name'); // => "value"

So your code could work like:-

$(".badge").click(function(){
    $(".badge").css("display","none");
    $.cookie('hide-badge', true, { expires: 7 });
});

$(function(){
  
  if($.cookie('hide-badge'))
    $(".badge").css("display","none");
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

<p class="badge">new</p>
like image 35
BenG Avatar answered Jul 12 '26 09:07

BenG