I'm just starting to learn Javascript; I do however have experience in programming using the C family of languages.
I'm basically trying to get a grasp on how the getElementById() function families work. To do this I'm trying to create a basic show/hide panel.
<div>
<div id="box1">
Title
<span class="time">Time</span>
<span class="else" style="display:none;">Something Else</span>
<a class="icon" href="#" OnClick="javascript:toggle('box1');">[-]</a>
<div class="content">Content</div>
</div>
</div>
Here is what I have so far for code:
function toggle(whichLayer)
{
var elem, vis;
if (document.getElementById) // this is the way the standards work
{
elem = document.getElementById(whichLayer);
}
vis = elem.style;
// if the style.display value is blank we try to figure it out here
if (vis.display == '' && elem.offsetWidth != undefined && elem.offsetHeight != undefined)
{
vis.display = (elem.offsetWidth != 0 && elem.offsetHeight != 0) ? 'block' : 'none';
}
vis.display = (vis.display == '' || vis.display == 'block') ? 'none' : 'block';
}
It currently just shows and hides the box1 div which is all the code is supposed to do. Here is what I would like to be able to do:
- I'd like to be able to toggle the [+] on click to [-] and vis versa.
- I'd like to be able to hide div.content
- I'd like to be able to toggle of the span from time visible to the other one and vis versa.
I can think about how to do this in pseudo code, but I don't know javascript well enough.
OnClick(string divId)
{
if (divId.Hide)
{
divId.span.else.display = block;
divId.span.time.display = none;
divId.a.icon.text = "[+]";
divId.div.content.display = none;
}
else //Show
{
divId.span.else.display = none;
divId.span.time.display = block;
divId.a.icon.text = "[-]";
divId.div.content.display = block;
}
}
I guess the part that I'm stuck on is where I select the classes inside of the id="box1" div. I don't know how to interate through them by class name. I'm found stuff using google on how to do a getElementByClass() implementation because JS doesn't have one, but its over my head.
Any help would be greatly appreciated.
javascript:prefixes; what you are actually doing there is defining a C-style label called ‘javascript’. No-one ever uses labels in JS. You're getting confused withjavascript:URLs, which also should never be used.<a class="toggler" href="#content1">, to point the destination of the link at the content it is referring to (which makes sense for non-JS browsers). Then in script at the end, scan the document for elements withclass="toggler"and attach an event handler directly to the element objects instead of an attribute. The event handler can readthis.href.hashto find out the ID of the element to show/hide.