Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  83] [ 6]  / answers: 1 / hits: 20505  / 12 Years ago, fri, april 27, 2012, 12:00:00

I have a problem with adding a cookie. Read a couple of answers, but it's hard to understand if you never worked with them before.



What I basically want is to add a cookie if someone click on the specified button. So for example, if person clicked on the like button, hidden content will be revealed no matter if he go forward/back or refresh page and cookie shall be removed after a couple of days.



What I used to hide the content is following:



HTML:



<div id=fd>
<p>Button from below will become active once you hit like button!</p>
<div id=get-it>
<a class=button><img src=img/get-button.png></a>
</div>
</div>
<div id='feedback' style='display:none'></div>


javascript:



FB.Event.subscribe('edge.create', function (response) {
$('#feedback').fadeIn().html('<p>Thank you. You may proceed now!</p><br/><div id=get-it><a class=button2 href=pick.html><img src=img/get-button.png></a></div>');
$('#fd').fadeOut();
});


However if I hit refresh or go back/forward on the content page, it will be hidden again. This is reason why I want to add a cookie on button hit. Anyone who can give me some explanations or example code?


More From » jquery

 Answers
44

I suggest using the jQuery-cookie plugin. Here's a few examples of usage:



// 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 });
});


You will also need to add a check that the cookie exists (for when the browser is reloaded:



if ($.cookie('the_cookie')) {
// Apply rule you want to apply
$('.ClassToSelect').css(display, none);
}

[#85925] Thursday, April 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;