0

I have read other questions in stackoverflow , But I am unable to make it working.Below Is the html and javascript I tried

    <div class="container wrapit" >
    <div id="one" style="display:none">
    one
    </div>
    <div id="two" style="display:none">
    two
    </div>
    <div id="three" style="display:none">
    three
    </div>
    </div>


    <div data-id="one" class="toggler">
    button1
    </div>

    <div data-id="two" class="toggler">
    button2
    </div>
 <div data-id="three" class="toggler">
    button3
    </div>

When I click button1 it must show only id one based on its data-id attribute and When I click button2 it must show ony id two and should hide others. Below is the code I tried

$( ".toggler" ).click(function() {

 var id = $(this).data('id');
   var $div = $('.wrapit > #'+ id );
    $div.show();

});

Here is fiddle -https://jsfiddle.net/zm631u6o/1/

NOTE : This is not duplicate because , right now it shows both one and two , I wanna hide other elements and show only one at a time

Vishnu
  • 2,372
  • 6
  • 36
  • 58

1 Answers1

2

Do you want something like

$(".toggler").click(function() {
$('.container div').hide(); //JUST ADD THIS LINE
  var id = $(this).data('id');
  var $div = $('.wrapit > #' + id);
  $div.show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container wrapit">
  <div id="one" style="display:none">
one
  </div>
  <div id="two" style="display:none">
two
  </div>
<div id="three" style="display:none">
three
  </div>
</div>


<div data-id="one" class="toggler">
  button1
</div>

<div data-id="two" class="toggler">
  button2
</div>
<div data-id="three" class="toggler">
  button3
</div>

If changes are there then inform me..

Dhara
  • 1,914
  • 2
  • 18
  • 37