Question

I have an idea how to implement this, but it doesn't seem that of all the similar posts, anybody is able to give a simple example. I want to simply store the value of the toggle state of "marketing-message-global" in a cookie. If the user clicks "hide-marketing-message-btn", the toggled state will be stored in a cookie. When the user refreshes the page, the stored toggle state will be used, and hide the div that was toggled off.

<div id="marketing-message-global">
</div>
<div id="hide-marketing-message-btn">
</div>

$(document).ready(function() {
 if $('#hide-marketing-message-btn").clicked()
 {
    $("#marketing-message-global").hide();
    $.cookie("toggle-state") == true;
 }

if ($.cookie("toggle-state") == true)
{
    $("#marketing-message-global").hide();
}
else if ($.cookie("toggle-state") == false)
{
$("#marketing-message-global").show();
}
 });
</script>
Was it helpful?

Solution

I used jquery cookie plugin (https://github.com/carhartl/jquery-cookie)

    $(function(){
       if($.cookie){
           //By default, if no cookie, just display.
           $("#marketing-message-global").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
    }

    $('#hide-marketing-message-btn').on('click', function(){
        $("#marketing-message-global").toggle();
        //Save the value to the cookie for 1 day; and cookie domain is whole site, if ignore "path", it will save this cookie for current page only;
        $.cookie("toggle-state", $("#marketing-message-global").is(':visible'), {expires: 1, path:'/'}); 
});

});

OTHER TIPS

I think this should work:

1) If you want to set the cookie by some events else:

$(document).ready(function() {
    if ($("#hide-marketing-message-btn").prop("hidden") == "hidden")
    {
        $("#marketing-message-global").hide();
        $.cookie("toggle-state") == true;
    }
    else
    {
        // ... 
    }
});

2) Setting cookie by clicking on div and performing toggle at once:

$(document).ready(function() {
    $("#hide-marketing-message-btn").click(function() { 
        if ($("#hide-marketing-message-btn").prop("hidden") == "hidden")
        {
            $("#marketing-message-global").hide();
            $.cookie("toggle-state") == true;
        }
        else
        {
            // ... 
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top