javascript - Is it possible to toggle different divs by clicking on different elements using the same function? -
say have 50 div
, this:
<div class="btn1"></div> //toggles first container appear <div class="btn2"></div> //toggles second container appear <div class="btn3"></div> //toggles third container appear
and 50 div
contain information, this:
<div class="container-1"><h1>this first container</h1></div> <div class="container-2"><h1>this second container</h1></div> <div class="container-3"><h1>this third container</h1></div>
is possible make corresponding div
toggle when each button clicked 1 function? have read little delegation , operating on parents/siblings seems work on multiple buttons opening same container, rather each button opening each container.
somehow don't think writing function every div way go.
yes possible. need add reference clicked object click event know show/hide
$(function() { $('.btn').on('click', function(e) { var $datatarget = $($(this).data('target')); $datatarget.show().siblings('.container').hide(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="btn btn1" data-target=".container-1"></div> //toggles first container appear <div class="btn btn2" data-target=".container-2"></div> //toggles second container appear <div class="btn btn3" data-target=".container-3"></div> //toggles third container appear <div class="container container-1"> <h1>this first container</h1> </div> <div class="container container-2"> <h1>this second container</h1> </div> <div class="container container-3"> <h1>this third container</h1> </div>
this show container targeted, hide other containers.
Comments
Post a Comment