dvlden
dvlden

Reputation: 2462

Cookie add on button hit

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?

Upvotes: 3

Views: 21173

Answers (2)

James Hill
James Hill

Reputation: 61872

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

Upvotes: 13

Yusuf X
Yusuf X

Reputation: 14633

Instead of cookies, I recommend you use localStorage.

Upvotes: 2

Related Questions