Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery toggle on individual divs

I'm trying to create a toggle effect using + and - boxes for showing and hiding divs. And example http://theodin.co.uk/tools/tutorials/jqueryTutorial/index.html

This is the script I'm using

$(function(){
        $('.block').hide();
            $('#show').toggle(function(){
                    $('.block').show(); 
                    $(this).attr("src","images/minus.jpg" );
            },function(){
                $('.block').hide(); 
                $(this).attr("src", "images/plus.jpg" );
            });
    });

The HTML

<div id="show"> Open <img id="show" src="images/plus.jpg"/> </div>
    <div class="block"> 
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    </div>  

It works fine with one div but I have multiple and when I click one, they all show. Is there a way to toggle them individually using the code I have?

like image 334
user499630 Avatar asked Nov 06 '22 06:11

user499630


1 Answers

Change the show ID to a class like this:

<div class="show"> Open <img src="images/plus.jpg" /> </div>
<div class="block">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>  

<div class="show"> Open <img src="images/plus.jpg" /> </div>
<div class="block">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>  

Then the jQuery becomes:

$('.show').toggle(function(){
  $(this).next('.block').show(); 
  $(this).children("img").attr("src","images/minus.jpg" );
},function(){
  $(this).next('.block').hide(); 
  $(this).children("img").attr("src", "images/plus.jpg" );
});

Here's an example.

like image 199
Gert Grenander Avatar answered Nov 09 '22 03:11

Gert Grenander