Every function call has its own "this" - that's just the way JavaScript
works.

To fix it, assign "this" - or better yet in your case, "$(this)" - into a
variable outside the click function. We can also avoid the repeated calls to
the same selector by using another variable:

$('.wallpaper').each(function(){
        var $wallpaper = $(this);
        var $anim = $wallpaper.find('.images > .anim').hide();

        $wallpaper.find('.buttons > .anim').click(function(event){
                $('p').toggleClass( 'rainbows' );
                $wallpaper.find('p').toggleClass('fraggle');
                // $anim.show();
                // $wallpaper.find('.images > .static').hide();
                return false;
        })
});

-Mike

> From: [email protected] 
> [mailto:[EMAIL PROTECTED] On Behalf Of milkshake
> Sent: Monday, November 19, 2007 8:03 AM
> To: jQuery (English)
> Subject: [jQuery] (this) question
> 
> 
> Hello, a beginners question:
> 
> */ JS
> ----------------------------------------------------- */
> 
> $('.wallpaper').each(function(){
> 
>       $(this).find('.images > .anim').hide();
> 
>       $(this).find('.buttons > .anim').click(function(event){
>               $('p').toggleClass( 'rainbows' );
>               $(this).find('p').toggleClass('fraggle');
>               // $(this).find('.images > .anim').show();
>               // $(this).find('.images > .static').hide();
>               return false;
>       })
> });
> 
> 
> */ HTML
> ----------------------------------------------------- */
> 
> <div class="wallpaper">
>       <div class="images">
>               <p class="static"><img src="blah-static.jpg" /></p>
>               <p class="anim"><img src="blah-anim.gif /></p>
>       </div>
>       <div class="buttons">
>               <p class="static"><a href="#">Static</a></p>
>               <p class="anim"><a href="#">Animated</a></p>
>       </div>
> </div>
> 
> It seems I'm not able to pass the (this) keyword on to the 
> click/event function.
> 
> $('p').toggleClass( 'rainbows' ); // works 
> $(this).find('p').toggleClass('fraggle'); // not working
> 
> Each ".wallpaper" div should be sandboxed so that the 
> methods(?) only work inside that particular div instance.
> Is there a better way to do this?
> (the commented out .show + .hide are what I'm really after, 
> just using toggleClass for testing).
> 
> Thanks in advance :)
> 

Reply via email to