Search code examples
jquerycssparentslidetoggle

Jquery hide and show css class but only content inside current div, not any other


I have loop in wordpress that generates a div with two divs inside and a hide and a show element like below -

<div class="vacancy-desc">
 <div class="short-desc">
   Content
 </div>                 
 <div class="full-desc">
   Content               
 </div>       
 <a href="#" class="link show">MORE <span class="fa fa-chevron-right"></span></a>
 <a href="#" class="link hide"><span class="fa fa-chevron-right"></span> LESS</a>
</div>

Because this is in the loop there may be several of these exact boxes on the same page.

I want to be able to click on the .show link to expand the .full-desc (which is hidden via css) and the .show to disappear, and the .hide to appear (which is also hidden by css). Then I want the opposite where I can click .hide it will toggle .full-desc shut, disappear and unhide .show.

I can get all this to happen but it targets every .hide .show on the page. What am I missing that allows me to create this script but only target the classes within its parent div?

<script>
$('.vacancy-desc a.show').click(function(event){
  event.preventDefault();
  $(this).prev().slideToggle('slow');
  $(this).hide();
});

$('.vacancy-desc a.hide').click(function(event){
  event.preventDefault();
  $(this).prev().slideToggle('slow');
  $(this).hide();
});
</script>

Solution

  • You could try something like this:

    <script>
        $('.vacancy-desc a.show').click(function(event){
            event.preventDefault();
            var $this = $(this);
            $this.parents('.vacancy-desc').find('.full-desc').slideToggle('slow');
            $this.hide();
            $this.parents('.vacancy-desc').find('a.hide').show();
        });
    
        $('.vacancy-desc a.hide').click(function(event){
              event.preventDefault();
              var $this = $(this);
              $this.parents('.vacancy-desc').find('.full-desc').slideToggle('slow');
              $this.hide();
              $this.parents('.vacancy-desc').find('a.show').show();
        });
    </script>