Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery toggle hide/show div; how to prevent to hide div when click again on the same anchor

I have 2 divs which toggle when click on anchor.
Click on anchor 1; div 1 is shown, div 2 is hide.
When clicking second time on anchor 1; div 1 also hides. This should not be!
How can i prevent that?

I tried this with if( !$(this).closest('li').hasClass('.active') ) { but this does not work

$('.showSingle').click(function() {

  if (!$(this).closest('li').hasClass('.active')) {

    $('.active').closest('li').removeClass('active');
    $(this).closest('li').addClass('active');
    $('.targetDiv').not('#div' + $(this).attr('target')).hide();
    $('#div' + $(this).attr('target')).toggle();

  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<li class="active">
  <a class="showSingle" target="1">Show div 1</a>
</li>
<li>
  <a class="showSingle" target="2">Show div 2</a>
</li>

<br /><br />

<section id="div1" class="targetDiv">
  Content div 1
</section>

<section id="div2" class="targetDiv" style="display:none;">
  Content div 2
</section>

Fiddle

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Almost.

This is simpler and works

$(function() {
  $('.showSingle').on('click', function() {
    const target = $(this).attr('target');
    const $li = $(this).closest('li');
    $('li.active').removeClass('active'); // remove all active 
    $li.addClass('active');
    $('.targetDiv').hide(); // hide all
    $(`#div${target}`).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<li class="active">
  <a class="showSingle" target="1">Show div 1</a>
</li>
<li>
  <a class="showSingle" target="2">Show div 2</a>
</li>

<br /><br />

<section id="div1" class="targetDiv">
  Content div 1
</section>

<section id="div2" class="targetDiv" style="display:none;">
  Content div 2
</section>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading