xhallix
xhallix

Reputation: 3011

jquery next() this

I stumpled upon a small problem.

Trying to make an easy accordian nav. with jquery, but noticed something I cannot figure out.

here's my code

<div class="box"> Item 1</div>
<div class="text"> Text Box </div>
<div class="box"> Item 2</div>
<div class="text"> Text Box 2</div>
<div class="box"> Item 3</div>
<div class="text"> Text Box 3</div>

JS

$('.box').click(function(){
    $('.text').slideUp()
    $(this).next().slideToggle()    
})

What I wonder is, if I use

    $(this).next().slideToggle()      

everything works fine.

Now I tried to replace (this) as following:

    $('.text').next().slideToggle() 

But the effect is different. I thought (this) would be related to the div-text or at least to something else in the DOM?

Upvotes: 1

Views: 149

Answers (2)

Adil
Adil

Reputation: 148140

The $(this) in the click event represent the source of event, on the other hand $('.text') represents collection of all the elements those have class text. $('.text').next().slideToggle() will call the slideToggle on the first element of collection returned by selector $('.text').

Upvotes: 3

Jai
Jai

Reputation: 74738

In short:

$(this) // <----Represents current target which got the event

while:

$('.text') // <--- this is a collection of all elems with class '.text' so all
           // -----will be getting events simultaneosly.

Upvotes: 1

Related Questions