Dan
Dan

Reputation: 1660

if child div exists bind event, if it does not then don't bind

I've just started learning jquery so please go easy.

I'm trying to create a slide out menu that when you click a button, the menu slides out showing the menu, when a menu item has been clicked the sub-menu relating to the selection will slide out and replace the existing menu but i'm stuck on a certain part. At the moment when you click on a list item, my jquery code is preventing the link being processed and instead shows the sub-menu which is correct but once you get to the end and there's no more sub menus the links don't work.

What i'm trying to achieve is if .menu ul li has a child div called sub-menu then prevent default, if it doesn't have a child div called sub menu then leave it alone.

I've searched all day and I've only started learning this last week.

Here's the html

  <ul class="menu">
    <li class="menu-item"><a href="one">1</a></li>
    <li class="menu-item"><a href="two">2</a>
      <ul class="sub-menu">
        <li class="menu-item"><a href="two-one">3-1</a></li>
      </ul>
    </li>
    <li class="menu-item"><a href="three">3</a>
      <ul class="sub-menu">
        <li class="menu-item"><a href="three-one">3-1</a></li>
        <li class="menu-item"><a href="three-two">3-2</a>
          <ul class="sub-menu">
            <li class="menu-item"><a href="three-two-one">3-2-1</a></li>
          </ul
        </li>
      </ul>
    </li>
    <li class="menu-item"><a href="four">4</a></li>
  </ul>

Here's the jquery part i'm stuck on

$('nav ul li').click(function(e) {
    e.preventDefault();
    $('.sub-menu').toggleClass('open');
});

Upvotes: 0

Views: 198

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

You simply need to use the :has() selector:

$('nav ul li:has(.sub-menu)').click(function(e) {

});

As a suggestion for performance, I recommend binding a delegate handler to the nav element, and dropping the unnecessary ul in the selection. You probably also meant to search within the matched element, rather than toggling all .sub-menu elements:

$('nav').on('click', 'li:has(.sub-menu)', function (e) {
    e.preventDefault();
    $(this).find('.sub-menu').toggleClass('open');
});

Upvotes: 1

JorgeeFG
JorgeeFG

Reputation: 5941

I am not that good but this can help:

if( $('#element').find('*').length > 0 ) {
  // Do something
  $('#element').click( function () { } );
}

Reference:

http://api.jquery.com/find/

You con achieve the same using children() instead of find('*').

http://api.jquery.com/children/

Upvotes: 0

Related Questions