Carpy
Carpy

Reputation: 1074

Announcement Bar, setting a cookie

I've a bar along the top of my website to announce announcements (like how stackoverflow does it with new badges etc). The code i'm using is as follows

html

<div id="announcement_popup" title="Special Announcement" style="display:none;">
    <h3>Announcement</h3>
    <a href="#" id="closeit">Close</a>
</div>

jquery

$("#announcement_popup").fadeIn("slow");
$("a#closeit").click(function() {
    $("#announcement_popup").fadeOut("slow");
    return false;
});

It all works fine but i'd like to be able to set a cookie using the jquery cookie plugin so when the user closes the bar, it won't show again for x amount of hours/days. Im stumped on how to do this.

Thanks

Upvotes: 4

Views: 1440

Answers (1)

Nick Craver
Nick Craver

Reputation: 630389

Let's say you wanted to hide it for 7 days, it would look like this:

if(!$.cookie('hideTopBar')) $("#announcement_popup").fadeIn("slow");
$("a#closeit").click(function() {
    $.cookie('hideTopBar', 'true', { expires: 7 });
    $("#announcement_popup").fadeOut("slow");
    return false;
});

Here we're checking if the cookie is set to any non-empty string initially, if it is then don't fade the bar in at all. In the click handler we're setting it that same 'hideTopBar' cookie to any non-empty strying, 'true' could be anything else as well...and using the expires option for 7 days.

expires takes a number of days (it can be a fraction!, e.g 1/24 for an hour) since that's the most common...if you want a different expiration date you can also calculate the Date yourself and pass that in directly.

Upvotes: 5

Related Questions