AlexB
AlexB

Reputation: 2184

Show/Hide jQuery, shows all of the divs instead of one that was clicked

I am trying to use jQuery show div, but the problem I have is that it all of the divs with same class are being shown instead of the one that was clicked.

So basically, once VIEW MORE is clicked, the div should be visible and VIEW MORE should be hidden, then if the VIEW MORE in another div is clicked, same thing should happen in that div too.

$('.show-more').click(function() {
  $('.text-hidden').show();
  $(this).hide()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="forms">
  <h2>New Forms</h2>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
  <ul>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>

<div class="forms">
  <h2>Old Forms</h2>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
  <ul>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>

I am not a big pro on jquery/javascript so please bear with me on this one.

Thanks

Upvotes: 1

Views: 87

Answers (2)

Use .next() to achive what you want

$(this).next(".text-hidden").show()

This will select the next element with the class text-hidden and show it

Example below.

$('.show-more').click(function() {
  $(this).next(".text-hidden").show();
  $(this).hide()
});
.text-hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="forms">
  <h2>New Forms</h2>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
  <ul>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>

<div class="forms">
  <h2>Old Forms</h2>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<span class="show-more">VIEW MORE</span>
<div class="forms text-hidden">
  <ul>
    <li>4</li>
    <li>5</li>
    <li>6</li>
  </ul>
</div>

Upvotes: 2

David
David

Reputation: 218877

This will target every matching element:

$('.text-hidden').show();

What you want instead is to traverse the DOM from the clicked element to find a specific element relative to that clicked element. From your HTML, it looks like what you want is the "next .text-hidden", which would be something like this:

$(this).next('.text-hidden').show();

Upvotes: 3

Related Questions