Search code examples
jqueryshow-hide

jQuery Show/hide divs on click, target only children


I need to show/hide divs on click, multiple times on the same page. Each button should affect its children only.

I can make it work for one container, like this:

HTML:

<div class="container">

  <div class="buttons">
    <a  class="showSingle" target="1">Div 1</a>
    <a  class="showSingle" target="2">Div 2</a>
    <a  class="showSingle" target="3">Div 3</a>
  </div>

  <div id="div1" class="targetDiv">Lorum Ipsum1</div>
  <div id="div2" class="targetDiv">Lorum Ipsum2</div>
  <div id="div3" class="targetDiv">Lorum Ipsum3</div>

</div>

JS:

jQuery(function(){

        jQuery('.showSingle').click(function(){
              jQuery('.targetDiv').hide();
              jQuery('#div'+$(this).attr('target')).show();
        });
});

But I can't for multiple container: JSFiddle

I know it sounds a stupid problem but I itried wrapping it in an each() function, or using children() but can't make it work. Thank you

NOTE: I can't add ids to containers as they're generated dynamically


Solution

  • Working fiddle.

    1. The id attribute should be unique in same document so you've to change your duplicate ids to classes.
    2. Don't use attribute like target directly in tag please use data-* attributes, so your attribute should be data-target.

      Example :

      <div class="container">
      
          <div class="buttons">
              <a  class="showSingle" data-target="1">Div 1</a>
              <a  class="showSingle" data-target="2">Div 2</a>
              <a  class="showSingle" data-target="3">Div 3</a>
              <a  class="showSingle" data-target="4">Div 4</a>
          </div>
      
          <div class="targetDiv div1">Lorum Ipsum1</div>
          <div class="targetDiv div2">Lorum Ipsum2</div>
          <div class="targetDiv div3">Lorum Ipsum3</div>
      
      </div>
      
    3. Use closest() with find() to show/hide you divs and .data() to get the value from data-* attributes :

      jQuery(function(){
          jQuery('.showSingle').click(function(){
              var target = jQuery(this).data('target');
              var parent = jQuery(this).closest('.container');
      
              parent.find('.targetDiv').hide();
              parent.find('.div'+target).show();
          });
      });
      

    Hope this helps.