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?
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");
}
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With