0

The menu is supposed to show sub-items upon hover. Here's the code (from http://docs.jquery.com/Cookbook/Navigation):

   <ul id="menu">
    <li class="menu">Sub 1
     <ul>
      <li>test 1</li>
      <li>test 2</li>
      <li>test 3</li>
      <li>test 4</li>
    </ul>
   </li>

   <li class="menu">Sub 2
    <ul>
      <li>test 1</li>
      <li>test 2</li>
      <li>test 3</li>
      <li>test 4</li>
    </ul>
  </li>
</ul>

jQuery code:

$(document).ready(function() {
var toggle = function(direction, display) {
return function() {
  var self = this;
  var ul = $("ul", this);
  if( ul.css("display") == display && !self["block" + direction] ) {
    self["block" + direction] = true;
    ul["slide" + direction]("slow", function() {
      self["block" + direction] = false;
    });
  }
};
}

$("li.menu").hover(toggle("Down", "none"), toggle("Up", "block"));
  $("li.menu ul").hide();
});

What is this in the toggle function above? How is the code working? What is being selected by $("ul", this); ?

1 Answer 1

2

The "this" refers to the jQuery object $("li.menu") - when the hover method call applies the toggle function to that object. $("ul", this) selects ul elements that are children of the context provided in the second argument ("this"), thus it selects the ul elements nested within the li.menu elements. Hopefully that makes the hover/toggle functions make sense.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! One more thing: What is the need to use self["block" + direction]? The code works fine without that also.
I'm not sure actually. I also could not see a difference in behavior. The purpose would be to prevent event queueing that could render an incorrect state, but it does seem redundant. Perhaps the author found it was necessary for older versions of jQuery or to solve a particular browser quirk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.