Beautiful Mike...that's exactly what I was wanting to know. Thanks a
lot!

On Sep 1, 11:20 am, "Michael Geary" <[EMAIL PROTECTED]> wrote:
> > > > Is there a way to pass arguments from one anonymous function, (in
> > > > either Toggle, or Hover) to the second?
> > > Closures are your friend:
>
> > > $('a.display').each(function() {
> > >      var $this = $(this), size = $this.attr('href'), toggle = $('.' +
> size);
> > >      $this.toggle(function() {
> > >          toggle.hide();
> > >      }, function() {
> > >          toggle.show();
> > >      });
>
> > > });
>
> One suggestion: Use $toggle instead of toggle, since it is a jQuery object.
> Either name works the same, of course, but the $ prefix (as used with $this
> in the example) is a handy way to remember which of your variables are
> jQuery result objects.
>
> > 1) I'm assuming from your reply that there's no way to do
> > this with plain ole hover/toggle then?
>
> Even if there were, the nice thing about a closure is that you can *always*
> use it, regardless of whether a particular API function has a special way of
> passing arguments through or not. So you don't have to research every
> function individually, just use a closure.
>
> > 2) What is a closure?
>
> When one function is nested inside another, the inner function can use the
> variables from the outer function. JavaScript looks up variables by starting
> with the innermost function, then working its way out through any nested
> functions.
>
> This works even if the outer function has already returned, as in the case
> above where the inner function is an event handler. JavaScript keeps the
> variables from the outer function available for this purpose.
>
> Here's a very detailed article on JavaScript closures:
>
> http://www.jibbering.com/faq/faq_notes/closures.html
>
> That article can be a bit overwhelming, but read it a few times and it will
> start to make sense. It's worth getting up to speed on closures since they
> are such a powerful feature of the language. I wish there were a simpler
> introduction to them somewhere. (Anybody know of one?)
>
> > 3) Is there any performance hit when doing .each (then
> > toggle) versus just doing .toggle?
>
> .toggle() calls .each() internally (indirectly through a call to .click()),
> so it probably doesn't make much difference. More importanly, calling
> .each() here allows a closure to be set up for each individual element, so
> there is a unique toggle variable (or as I suggested, $toggle) for each
> element.
>
> -Mike

Reply via email to