Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

jQuery hiding/showing sections based on .index()

I have 3 titles that when clicked they have their own description. I only want the description that matches to the title to be displayed.

$('.descriptions p').hide();

$('.titles h3').click(function() {
  var a = $(this).index();
  
  ('.descriptions p').index(a).fadeIn();
})
.titles h3 {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="titles">
  <h3>Title One</h3>
  <h3>Title Two</h3>
  <h3>Title Three</h3>
</div>

<div class="descriptions">
  <p>Description One</p>
  <p>Description Two</p>
  <p>Description Three</p>
</div>

Upvotes: 0

Views: 32

Answers (1)

aleksandar
aleksandar

Reputation: 2399

You had some little mistakes.

.index() vs .eq()

The .eq() function returns the object at the specified location in the array returned by the jQuery selector.


The .index() function takes a jQuery selector as parameter. This function is run on something that is already a jquery/DOM Element. Based on the selector passed to .index() jQuery will determine what the index is of the DOM element it was run on.


Here is the corrected code.

$(document).ready(function () {
    $('.descriptions p').hide();

    $('.titles h3').click(function () {
        var a = $(this).index();

        $('.descriptions p').eq(a).fadeIn();
    })
});
.titles h3 {
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="titles">
     <h3>Title One</h3>
     <h3>Title Two</h3>
     <h3>Title Three</h3>

</div>
<div class="descriptions">
    <p>Description One</p>
    <p>Description Two</p>
    <p>Description Three</p>
</div>

Upvotes: 1

Related Questions