stephenmurdoch
stephenmurdoch

Reputation: 34613

jQuery code causes all divs of a particular class to toggle when link is clicked

I have some jquery code that displays and hides a div when a link is clicked.

$(document).ready(function() {
  $(".tracklist").hide();
  $('.link').bind('click', function(e) {
    $('.tracklist').toggle('slide', {easing: 'easeOutQuint', direction: 'down'}, 1000);
    return false;
  });
});

This code toggles all divs named tracklist when I press any link. Not good.

I need to find a way of ensuring that each link affects only one tracklist div

Edit

My markup - the code below appears several times on each page:

<article class="podcast">
  <ul class="buttons">
    <li>
      <a class="link" href=>"#">Tracklist</a>
    </li>
    // other links removed 
  </ul>

  <div class="tracklist">
    Content that I want to toggle
  </div>
</article>

Upvotes: 1

Views: 370

Answers (3)

stephenmurdoch
stephenmurdoch

Reputation: 34613

Fixed:

$(document).ready(function() {
 $(".tracklist").hide();
 $('.link').bind('click', function(e) {
  $(this).closest('.podcast').children('.tracklist').toggle('slide', {easing: 'easeOutQuint', direction: 'down'}, 1000);
       return false;
    });
});

Now it works :) Thanks to @Loktar who got me 90% of the way there

Upvotes: 1

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

You can add a rel attribute to the link, that matches track lists id.

For example:

<div class="tracklist" id="track-1"></div>
<div class="tracklist" id="track-2"></div>
<div class="tracklist" id="track-3"></div>

<a href="#" class="link" rel="1">Show 1</a>
<a href="#" class="link" rel="2">Show 2</a>
<a href="#" class="link" rel="3">Show 3</a>

<script>
$("a.link").click(function(){
  var el = $(this);
  $("div.tracklist#track-" + el.attr("rel")).show();
});
</script>

Upvotes: 1

Loktar
Loktar

Reputation: 35309

try

$(document).ready(function() {
    $(".tracklist").hide();
    $('.link').bind('click', function(e) {
       $(this).children('.tracklist').toggle('slide', {easing: 'easeOutQuint', direction: 'down'}, 1000);
    return false;
 });
});  

Upvotes: 2

Related Questions