I am currently trying to use jQuery to toggle the appearance of a shoutbox
and remember the state (hidden / visible) from page to page. The problem I am having is in getting a cookie set to remember the state.
The code I have so far is below, but it doesn't seem to be executing the if
statement correctly. Any ideas why?
function show_shoutbox() {
$('#SB').toggle("fast");
if ($('#SB').css('display') == "none") {
document.cookie = "displaysb=false;";
} else {
document.cookie = "displaysb=true; ";
}
}
I am fairly new to JavaScript and jQuery - so I apologize in advance if the answer is obvious. I'm hoping to learn.
Try
if ( $('#SB').is(':visible') ) {
...
}
It's normalized to work a little better than checking display
.
use $('#SB')[0]
instead of $('#SB')
. this part of code returns an array of all elements that satisfy the requirements. and if you only have one element with this ID, the first element with the index 0
is the element you are searching for.
document.cookie doesn't work that way. Check out:
http://www.quirksmode.org/js/cookies.html
It even has code at the end of it:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Cache your element for efficiency
var sb=$('#SB');//cache once outside the function
function show_shoutbox() {
sb.toggle("fast");
if ( sb.is(':visible')) {//do your business
}
else { //do something else
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.