Currently I’m able to click on a title and then the information relating to the title is shown. If another title is selected then it is opened either below or above the previous open title, if the title is clicked a second time then they are hidden.
What I’m trying to do is, if a title is already open, upon clicking on another title it would hide the previous and show the most recently clicked.
The javascript I’m currently working with is the following
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
function hide(divID) {
var item = document.getElementById(divID);
if (item == 'element_name') {
item.className=(item.className=='hidden');
}
}
Suggestion #1
Give all of the title elements a common class name, e.g.
title, then usedocument.getElementsByClassName('title')to find all of the title elements, and hide them all before “unhiding” the clicked title, if the clicked title element is hidden.That being said, you’ll need to modify the two functions you wrote to accommodate multiple classes in an element. You can easily set multiple class names via
element.className = 'unhidden title', but your code will be rather inflexible. Your code will quickly become unwieldy as you try to modify your list of class names via theString#splitmethod, looping through the classes to find and delete the hidden or unhidden classes.Suggestion #2
Do not to use an unhidden class. Presumably, your unhidden class is defined as follows:
This class becomes much less useful if you have inline elements as well that you want to unhide because you’ll need another class:
If you simply define:
and add or remove the hidden class to hide or show the element, then you can avoid this issue altogether. You’ll still have the issue of dealing with multiple class names in an element, however.
Suggestion #3 (ideal)
Use jQuery or Zepto.js to handle DOM traversal and manipulation, it will make your life much easier. You’ll no longer need to manipulate classes at all in this case, you can simply hide and show the elements directly with convenience methods. Include jQuery:
Assuming the following markup:
and the following css:
you can do the following to accomplish your goal in a flexible manner:
I hope this helps, good luck!