Skovsgaard
Skovsgaard

Reputation: 369

How to set a cookie to hide a notice bar on second page load?

This is what I wan't:

This is my HTML:

<div id="cookie-message">
    <span>Cookie notice here <a href="#">Read more</a> <a href="#" id="cookie-message-close">Ok</a></span>
</div>

How can I do this with jQuery?

Thanks!

Upvotes: 0

Views: 2318

Answers (2)

Skovsgaard
Skovsgaard

Reputation: 369

Thanks a lot for your response, Henrique. However I couldn't get it to work duo to a "jQuery $.cookie is not a function" error.

I found out that "jQuery Cookie" is deprecated and js-cookie is the new version. By including that and changing the old cookie functions to the new ones it now works perfectly!

This is my final jQuery code, using "js-cookie":

window.addEventListener('load', function(){
    jQuery('#cookie-message-close').click(function(){
        jQuery('#cookie-message').hide();
    });

    if (!Cookies.get("cookie-message-bar"))
    {
        jQuery('#cookie-message').show();
        Cookies.set('cookie-message-bar', true, { expires: 60 });
    }
});

Note that I've changed $ to jQuery because of Wordpress' noConflict() mode, since I'm developing in Wordpress.

Upvotes: 0

You can use a API to deal with cookies, makes the things much more easy.

First of all you put display: none; in the div cookie-message.

About the logic of hidden or not the notice, you can put a listener in the first load of the window:

window.addEventListener('load', function(){...});

this way you can get the moment when the window is loaded. If in this moment there is no cookie for notice read, you show the div ($('#cookie-message').show(), and then you set up a cookie. If there is a cookie for that already set, you do nothing.

About the OK click, set up a click listener in the link to hide the notice div ($('#cookie-message').show()).

To help you, I make a simple example example of what I said.

Upvotes: 3

Related Questions