I am developing a website and I can’t use jQuery (no discussion about this), so pure javascript and a custom javascript framework is used.
Actually I have found a situation that I don’t know how to handle:
I’ve a group of selectors, that for each one I add a “onclick” event to display / hide a div.
For example:
<div id="menu">
<div class="menu-item">
<div class="arrow">
<a class="down">Open / Close</a>
</div>
Menu Item
<div class="extramenu hidden">
Extra menu items
</div>
</div>
<div class="menu-item">
<div class="arrow">
<a class="up">Open / Close</a>
</div>
Menu Item 2
<div class="extramenu">
Extra menu items
</div>
</div>
<div class="menu-item">
<div class="arrow">
<a class="down">Open / Close</a>
</div>
Menu Item 3
<div class="extramenu hidden">
Extra menu items
</div>
</div>
</div>
I select all “div.menu-item .arrow a” items, so I’ve 3 items. For each item I add a onclick event (that actually works fine).
What I need to archive is how to select the “closest” class .extramenu inside the div.menu-item. Then detect if the <a /> have a class .up or .down and if class == .up, add the class hidden; and if class == .down, remove the class hidden.
This a concept of what have to do, it’s not javascript code:
var elements; // my list of elements
each(elements, function(element) {
// here element is pointing to the ANCHOR
add_event(element, "onclick", function(e) {
var submenu; // here I need to detect the submenu closest to my anchor
var state; // here I need to know if the anchor has class up or down
if (state == "up")
{
add_class(submenu, "hidden"); // hide the submenu div
remove_class(element, "up"); // remove the class up
add_class(element, "down"); // and add the class down
}
else if (state == "down")
{
remove_class(submenu, "hidden"); // remove the class to show the menu
remove_class(element, "down"); // remove the class down
add_class(element, "up"); // and add the class up
}
});
});
Thank you guys and sorry if it’s not well explained, I did my best!
element.querySelectorAllallows you to select elements by CSS selector.element.classListallows you to access the classes of an elementYou can write the rest of the pseudo code yourself.
I’m assuming your already using Modernizr for supporting legacy browsers like IE8. If your not, then do so.