[Javascript] [Beginner] What is going on with my show/hide function?

Peter Brunone peter at brunone.com
Mon Nov 13 11:47:48 CST 2006


		Hi Mark,

   Not being an expert on accessibility, I have to ask:  Is there a reason why you're using the onclick event of a link to do this?  I would imagine that the changing window.location might have something to do with the problem, but I could be wrong.  If you plan to continue with that approach, you should probably change your event handler code to look like this:

onClick="return toggleDiv('divID');"

and return false at the end of the JS function, so your link won't mess with the window location.

   Beyond that, you may or may not know that the div tag's default display setting is "block", not "inline".  If you're doing this for stylistic reasons, ignore that part.

   However, I think the problem may lie with the way you're setting display.  You originally have no setting in the style.display attribute, since you're setting the Class instead.  What's probably happening is that you are overriding the value of display in the class, by setting it directly on the element.  In a nutshell, if you're going to use the classes, you need to keep working with them instead of setting style.display afterward.

   Does that make sense?  It's Monday morning and I'm still recovering from a nasty cold, so my head isn't quite back where it should be.

Peter

				From: Mark Kelly javascript at wastedtimes.net

Hello.

I have a written a simple function to toggle the visibility of a 
that 
is, it seems to me, behaving oddly. On divs that are initially shown, the 
function works perfectly, toggling the content visibility. On divs that 
are initially hidden, the first click appears to do nothing but 2nd and 
subsequent clicks work fine. The code seems to me (as a beginner to 
javascript but not programming) to be so simple I can't imagine what I'm 
doing wrong.

I set the initial display value explicitly by setting the div class to 
either .shown or .hidden just to set the display property.

Any advice is appreciated.

Mark

===============================================
JAVASCRIPT
===============================================
function toggleDiv(divID) {
myReference = getRefToDiv(divID);
if(!myReference) {
window.alert('Failed to get a reference to the named DIV');
return;
}
if(myReference.style) {
if(myReference.style.display != 'none') {
myReference.style.display = 'none';
} else {
myReference.style.display = 'inline';
}
}
}
===============================================
CSS
===============================================
.hidden {display : none;}
.shown {display : inline;}
===============================================
HTML 
===============================================
Directories
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.evolt.org/pipermail/javascript/attachments/20061113/bffedb0b/attachment.htm>


More information about the Javascript mailing list