Next, we'll demonstrate a simple
Accordion
. In this example, we'll change the sidebar navigational boxes into expandable modules. Just follow the steps!1)Using the Joomla! template editor (instructionshere), add this code just above the
</head>
tag:
<script>
window.addEvent(
”
domready
”
, function( ){
var
togglers = $$(
”
.module_menu h3
”
);
var
elements = $$(
”
.module_menu ul.menu
”
);for(
var
i = 0; i < elements.length; i++ ) {
if(elements[i].previousSibling.previousSibling == null){elements.splice( i, 1 );i--;}
}
var
navAcc = new Accordion( togglers, elements );});
</script>
2)Voil
á
! Now your navigation is an accordion!How does all this coding work?
(Again, this can get pretty far in depth, so only read onif you feel fully comfortable with Javascript)
Like the
Tips
example, this waits for the event
'domready'
to trigger. At that point, it makes two variables:
togglers
, which holds the titles of all the navigation boxes (e.g. “Key Concepts”), and
elements
, which holds the lists of linksinside the boxes (e.g. “Joomla! Home”). Both of those variables are
arrays
, which are simplylists of data.Some of the navigation boxes don't have titles. If they don't have titles, and they wereput into the accordion, there would be no title to click on in order to view the links...It would bea huge mess. To counteract this, we loop through everything in the
elements
variable, andcheck that the HTML tag behind the element exists. If it does exist, we just move on to thenext element. However, if it doesn't exist, we remove it from
elements
with the function
splice()
.
splice()
takes two arguments when deleting elements from an array (
elements
): theindex, or number in the
elements
array where something is stored, and the number of indexesto delete. We supply it with the variable
i
, which holds the index of the HTML tag in the
elements
variable currently being checked. Next, we give it the number
1
, because we onlywant to remove 1 index.If we delete an index from
elements
, we must also subtract 1 from
i
. If we don't, it willskip right over one index in
elements
. It's a bit tough to comprehend, so I'll give you a better explanation: If we're checking index
3
in a
4
element array:
Element 1Element 2Element 3Element 4
Element
3
is then removed. Element
4
is moved to where element
3
used to be, and isthen known as element
3
.
Element 1Element 2Element 3 4
So, if we don't subtract 1 from
i
, it will be checking the nonexistent element
4
. I hopethat helped you understand arrays a bit better!Once we've looped through all of
elements
, we finally create the Accordion. The firstargument is
togglers
and the second is our filtered
elements
.