CMSCSS
CMSCSS

Reputation: 2176

Do jQuery's selectors work like CSS?

I'm trying to modify a drop down menu from Code Drops here: http://tympanus.net/codrops/2013/03/05/horizontal-drop-down-menu/

Mods:

I've added a close icon and both the icon and the menu item that triggers the dropdown have a .trigger class - however, I doesn't understand how to get jQuery to use all items with a class of .trigger - it will only use the first child and nothing deeper.

Here's the jQuery that seems to bind the trigger:

  var $listItems = $( '.dropdown-menu'),
    $menuItems = $listItems.children( '.trigger' ),
    $body = $( 'body' ),
    current = -1;

And here's the markup:

<div class="dropdown-menu">
  <ul>
    <li>
      <a class="trigger" href="#">Menu</a>
      <div class="dropdown">
        <div class="dropdown-inner">
          <a class="trigger" href="#">Close</a>
          <h4>Your cart</h4>
        </div>
      </div>
    </li>
  </ul>
</div>

Is there a way to get jQuery to see the Close button which is another couple of levels deeper?

And is there a way to trigger the close if the page is clicked?

Hope that makes sense - any pointers in the right direction would be much appreciated as searching hasn't yielded anything specific (probably not using the right search terms).

Cheers

Ben

Upvotes: 0

Views: 47

Answers (1)

jfriend00
jfriend00

Reputation: 707158

Your life is made more complicated by the fact that you are using .trigger for multiple types of objects so you have to distinguish which type of object by the selector you use before .trigger and .children() only looks for immediate children (not deeper than that).

This line:

$menuItems = $listItems.children( '.trigger' ),

will only look for immediate children of $listItems which isn't where .trigger is. You probably want to use .find() to look for at all descendants and if you want to avoid the close button .trigger, then you have to specify some context before the .trigger to only get the ones you want:

$menuItems = $listItems.find( 'li > .trigger' ),

This finds only .triggers that are an immediate descendant of an <li>.


Or, just do it in one selector:

$menuItems = $( '.dropdown-menu li > .trigger')

To get the close button .trigger and only that trigger, you can do this:

$close = $(".dropdown-menu .dropdown .trigger")

If you want to bind an event handler to the close item in your HTML, you could do this:

$(".dropdown-menu .dropdown .trigger").click(function(e) {
    // do whatever you want to do when the Close item is clicked
    return false;
});

It would be a lot easier to target the close menu item separately if you gave it a unique class name.

Upvotes: 1

Related Questions