3
\$\begingroup\$

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');
});
\$\endgroup\$
  • 1
    \$\begingroup\$ Hi, welcome to CR! If this post is meant as a comment to the accepted answer here, and you don't have enough rep to comment on other posts, know that you can comment on your question and use @JohnMark13 notation to make sure the intended user gets notified of your comment (sorry to ping you like this JohnMark13). \$\endgroup\$ – Mathieu Guindon Oct 30 '13 at 16:43
2
\$\begingroup\$

I think that all you are looking for is:

//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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.