patternjavascriptMinor
Calling individual classes for navigation items
Viewed 0 times
individualnavigationitemsforclassescalling
Problem
I have navigation items that are created dynamically with PHP. I wrote this because I need to add individual classes and fire them individually. My code works, but I want a way of refining it no matter how many items are added to the navigation via the backend. Is there a way of doing this so I don't have to add 20
.slideToggle lines of code? //Adds a CSS Selector to items we need to target individually
jQuery('#sidr ul li').has('ul').each(function(i){
jQuery(this).addClass('has-sub-'+(i+1));
});
jQuery('#sidr ul li ul').has('li').each(function(i){
jQuery(this).addClass('sub-'+(i+1));
});
//Toggles a 'clicked' CSS Selector and reveals the Sub-Menus
jQuery('li.has-sub-1').click(function(){
jQuery('#sidr ul li ul.sub-1').slideToggle(200);
});
jQuery('li.has-sub-2').click(function(){
jQuery('#sidr ul li ul.sub-2').slideToggle(200);
});
jQuery('li.has-sub-3').click(function(){
jQuery('#sidr ul li ul.sub-3').slideToggle(200);
});
jQuery('li.has-sub-1, li.has-sub-2, li.has-sub-3, li.has-sub-4, li.has-sub-5, li.has-sub-6').click(function(){
jQuery(this).toggleClass('clicked');
});Solution
I think that all you are looking for is:
If you cannot rely on a selector (like I used above) to find the elements that you are interested in, or if you cannot add classes to the elements when the page is assembled then you could add the class in code:
Now you can use:
This also saves re-evaluating the various selectors, which is much more efficient.
//assumes sidr is top level container for menu
//you should consider adding a generic class to menu items when page is assembled
jQuery('#sidr > ul > li').click(function() {
$this = jQuery(this);
$this.find('ul').slideToggle(200);
});If you cannot rely on a selector (like I used above) to find the elements that you are interested in, or if you cannot add classes to the elements when the page is assembled then you could add the class in code:
jQuery('#sidr ul li').has('ul').addClass('hasSubMenu');Now you can use:
jQuery('.hasSubMenu').click(function() {
$this = jQuery(this);
$this.find('ul').slideToggle(200);
$this.toggleClass('clicked');
});This also saves re-evaluating the various selectors, which is much more efficient.
Code Snippets
//assumes sidr is top level container for menu
//you should consider adding a generic class to menu items when page is assembled
jQuery('#sidr > ul > li').click(function() {
$this = jQuery(this);
$this.find('ul').slideToggle(200);
});jQuery('#sidr ul li').has('ul').addClass('hasSubMenu');jQuery('.hasSubMenu').click(function() {
$this = jQuery(this);
$this.find('ul').slideToggle(200);
$this.toggleClass('clicked');
});Context
StackExchange Code Review Q#31902, answer score: 2
Revisions (0)
No revisions yet.