Vertisan Vertisan - 5 months ago 7
jQuery Question

Multiple selected link and showed multiple div

I have somethink like this, but now I want to show multiple divs at same time, ex. I selected 'Div 1' and it show his div, now I click 'Div 2' and I want to stay content of 'Div 1' and show 'Div 2'. Anyone can help?

<div class="btn-group" role="group" aria-label="">
<a id="showAll" class="btn btn-primary">Wszystkie elementy</a>
<a class="showSingle btn btn-primary" data-target="1">Div 1</a>
<a class="showSingle btn btn-primary" data-target="2">Div 2</a>
<a class="showSingle btn btn-primary" data-target="3">Div 3</a>
<a class="showSingle btn btn-primary" data-target="4">Div 4</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 id="div4" class="targetDiv">Lorum Ipsum4</div>


.

$('.showSingle').click(function() {
$('.targetDiv').hide();

$('#div' + $(this).attr('data-target')).show();
$('.btn').removeClass('active');
$(this).addClass('active');
});


https://jsfiddle.net/42uwvhx4/

Answer

You just want a simple toggle. By modifying your example, this is how I accomplished it:

JS

$('#showAll').click(function() {
    $('.btn').addClass('active');
    $('.targetDiv').show();
    $(this).addClass('active');
});

$('.showSingle').click(function() {
    $('#div' + $(this).attr('data-target')).toggle();
    $(this).toggleClass('active');
});

Markup

<div class="btn-group" role="group" aria-label="">
  <a id="showAll" class="btn btn-primary active">Wszystkie elementy</a>
  <a class="showSingle btn btn-primary active" data-target="1">Div 1</a>
  <a class="showSingle btn btn-primary active" data-target="2">Div 2</a>
  <a class="showSingle btn btn-primary active" data-target="3">Div 3</a>
  <a class="showSingle btn btn-primary active" data-target="4">Div 4</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 id="div4" class="targetDiv">Lorum Ipsum4</div>

Fiddle: https://jsfiddle.net/hescano/42uwvhx4/2/

Notice the use of the .toggleClass() and .toggle() to accomplish the desired behavior.