Mecom
Mecom

Reputation: 411

Jquery toggle not working after adding cookie

Trying to maintain the last toggle state by adding a cookie https://github.com/carhartl/jquery-cookie. here is what I tried doing.

<html>
<head>
</head>
<body>
    <p>Lorem ipsum.</p> 
    <button>Toggle</button>
</body>
</html>

and then the jQuery and the Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        if ($.cookie){
            $("p").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true'); 
        }

    $("button").on('click', function(){

    $("p").toggle();
        $.cookie("toggle-state", $("p").is(':visible'), {expires: 1, path:'/'}); 
    });
});
</script>

Fiddle

I want the cookie to remember the last state the toggle, whether hide or display, it was in for a day.

Not working. Why?

Upvotes: 3

Views: 89

Answers (1)

SurudoiRyu
SurudoiRyu

Reputation: 321

You are not closing your first click event, due to errors your code will not run propperly.

$("button").click(function() {

When you close it all is working fine:enter image description here

Working Code:

$(document).ready(function() {
    $("button").click(function() {
        if ($.cookie){
            $("p").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true'); 
        }
    });

    $("button").on('click', function() {
        $("p").toggle();
        $.cookie("toggle-state", $("p").is(':visible'), {expires: 1, path:'/'}); 
    });
});

Upvotes: 1

Related Questions