views:

43

answers:

3

I'm trying to use jQuery to toggle the appearance of a shoutbox and remember that state from page to page. My problem is getting the cookie that remembers the state set. Here's the code I've come up with so far, 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; ";}
}

My experience with Javascript and jQuery is minimal, so I apologize if this is a stupid question.

A: 

Try

if ( $('#SB').is(':visible') ) {
    ...
}

It's normalized to work a little better than checking display.

Alex Sexton
I tried this... it's still not working.
waiwai933
It's not really a matter of that working or not. That's the code to check to see if an element is visible with jQuery. Voting down answers because your code is broken hardly seems intuitive or helpful. "it doesn't seem to be executing the if statement correctly" - I succinctly described to you how to do this. Please rephrase your question if you don't like getting answers to the one you asked.
Alex Sexton
Actually, it wasn't me who downvoted... any case, I did test your code with alert boxes, and it always told me it was visible, whether it actually was or not.
waiwai933
You should probably submit a bug to jQuery along with a test case http://docs.jquery.com/Selectors/visible as you seem to have found a bug, then.
Alex Sexton
A: 

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);
}
Malfist
Sorry, can you explain what I'm doing wrong? While the code is helpful, I want to know *why* something is wrong.
waiwai933
A: 

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
  }
}
czarchaic
That doesn't answer the question at all.
Malfist