Barry
Barry

Reputation: 593

Toggle single Div layer using jQuery

At runtime I have a loop that creates a number of divs with the same class depending on the number in the database.

<div class="show">....</div> 
<div class="show">....</div>  
<div class="show">....</div>  

I want to display this div using the slideToggle() function with jQuery. For each of these I have a separate hyperlink which when clicked should display the div. Also there are a number of tags in between the hyperlink and the div that I want to toggle.

<div>
<div>
<a href="#" class="display">View</a>  

</div>
    <br />
    </div>
    <div>
        <div class="clear"></div>
      </div>


<div class="show">....</div>

<div>
<div>    
<a href="#" class="display">View</a>  
</div>
    <br />
    </div>
    <div>
        <div class="clear"></div>
      </div>



<div class="show">....</div> 

<div>
<div>
<a href="#" class="display">View</a>  

</div>
    <br />
    </div>
    <div>
        <div class="clear"></div>
      </div>


<div class="show">....</div>   

$(function () {    
     $(".display").click(function(){    
         $(".show").slideToggle();    
         return false;     
      });  
});

Naturally when this is called each div layer is toggled, regardless of which hyperlink is clicked. I want to just toggle the div closest to the given hyperlink.

Thanks in advance.

Upvotes: 3

Views: 849

Answers (3)

Scoop
Scoop

Reputation: 310

Or while you loop through creating your divs, can you add (for example) a rel value that's incremented by one every time? Giving you something like...

<a href="#" class="display" rel="1">View</a>
<div class="show" rel="1">....</div>
<a href="#" class="display" rel="2">View</a>
<div class="show" rel="2">....</div>
<a href="#" class="display" rel="3">View</a>
<div class="show" rel="3">....</div>

This would then link the two divs so that you could get the rel value of your clicked element and use that to identify the shown / hidden div.

<script type="text/javascript">
$(function () {
$(".display").click(function () {
var element_id = $(this).attr('rel');
$(".show").attr('rel', element_id).slideToggle();
return false;
});
});

Upvotes: 0

benhowdle89
benhowdle89

Reputation: 37504

$(function () {
  $(".display").click(function () {
  $(this).next.(".show").slideToggle();
  return false;
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630627

Find the <div> relatively by going from this using tree traversal functions, like this:

$(function () {
  $(".display").click(function () {
    $(this).next().slideToggle();
    return false;
  });
});

In this case since it's the next sibling element we care about, use .next(), if the structure is different from the question, you'll need to adjust it accordingly, go get from the <a> you clicked on (this) to the <div> you want to toggle.

Upvotes: 2

Related Questions