Toggle image based on cookie value
Im using a couple of JS functions to set a cookie named 'visible'
with the value of either yes
or no
.
Essentially Im using these values to decide if a <div>
is visible or hidden.
I've on开发者_如何转开发ly just added the cookie, previously I had been using two images 1. Show 2. Hide as a button to hide and show the <div>
like this:
HTML:
<img class="show" title="Show" alt="Show" src="images/show.png" />
<img class="hide" title="Hide" alt="Hide" src="images/hide.png" />
JQUERY:
$("#tool").click(function() {
$(".help").slideToggle();
$("#wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() {
$("#tool img").toggle();
});
});
However I have now added the Cookie into the mix:
$("#tool").click(function() { if(get_cookie('visible')== null) { set_cookie('visible','no'); } else { delete_cookie('visible'); } $(".help").slideToggle(); $("#wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#slider img").toggle(); }); });
So the .toggle() no longer matches the state of the <div>
When the cookie value = no the show.png
should be visible
When the cookie value = yes then the hide.png
should be visible
Can anyone suggest how i can ammend this?
To make things easier I just didn't delete the cookie. And simply set it every time.
$("#tool").click(function () {
var cookie = get_cookie('visible');
if (cookie == null) {
set_cookie('visible', 'no');
cookie = get_cookie('visible');
}
if (cookie.value == 'yes') {
set_cookie('visible', 'yes');
$(".help").slideDown();
$("#wrapper").animate({
opacity: 1.0
}, 200).slideDown(200, function () {
$("#tool img").show();
});
} else {
set_cookie('visible', 'no');
$(".help").slideUp();
$("#wrapper").animate({
opacity: 1.0
}, 200).slideUp(200, function () {
$("#tool img").hide();
}
}
};
document.getElementsByClassName('show')[0].src = get_cookie('visible') ? 'images/hide.png' : 'images/show.png';
精彩评论