JQuery not working after adding cookie
Trying to keep 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 jQuery and 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>
I want the cookie to remember the last state it switched, whether it was hide or show, it was during the day.
Does not work. Why?
+3
source to share
1 answer
You are not closing your first click event, due to errors, your code will not run.
$("button").click(function() {
When you close everything works fine:
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:'/'});
});
});
+1
source to share