Vinicius Martinson
Vinicius Martinson

Reputation: 95

jQuery working for multiple buttons and divs

I am having some trouble on making a button only to show one div, not all of them.

Here's my JS code:

$('.show_avatar').click(function(){
$('.avatar').toggle('slow',function() {
    });
});

Here's my HTML:

<input class="show_avatar" type="button" value="Show"></input>
     <div class="avatar" style="display:none" class="text-center">
       <%= image_tag d.avatar.url(:medium) %>
     </div>

My HTML is in a loop, so it generates multiple buttons with multiple images. When I click in any of the buttons (.show_avatar), all the divs appear (.avatar). I know why this happens, but I don't know how to fix it.

I thank you in advance.

Upvotes: 0

Views: 48

Answers (2)

Popnoodles
Popnoodles

Reputation: 28419

Demo

Without needing any changes to the given HTML, you want to target the element that is the first match of .avatar after the button that you click. You can use next().

$('.show_avatar').click(function(){
    $(this).next('.avatar').toggle('slow',function() {
    });
});

Upvotes: 2

Tom Nolan
Tom Nolan

Reputation: 1957

You could wrap each in a wrapper

<div class="wrap">
    <input class="show_avatar" type="button" value="Show"></input>
    <div class="avatar" style="display:none" class="text-center">
        <img src="http://placehold.it/150x150">
    </div>
</div>

and change it to only call it's sibling:

$('.show_avatar').click(function(){
$(this).siblings('.avatar').toggle('slow',function() {
    })
});

http://jsfiddle.net/e629orfb/

Upvotes: 0

Related Questions