javascript - Expand / Collapse div by clicking another -
i'm looking create div expands , collapses when separate, non-parent div element clicked.
below example of expanding/collapsing effect , have been messing around with. unsure how best modify code below could, say, click on div located in sidebar, , cause div located below header say, expand/collapse, pushing content below downwards.
the contents of expanding/collapsing div in question might search bar instance, can shown/hidden user clicking on sidebar button.
$(".header").click(function () { $header = $(this); //getting next element $content = $header.next(); //open content needed - toggle slide- if visible, slide up, if not slidedown. $content.slidetoggle(500, function () { //execute after slidetoggle done //change text of header based on visibility of content div $header.text(function () { //change text based on condition return $content.is(":visible") ? "collapse" : "expand"; }); }); });
.container { width:100%; border:1px solid #d3d3d3; } .container div { width:100%; } .container .header { background-color:#d3d3d3; padding: 2px; cursor: pointer; font-weight: bold; } .container .content { display: none; padding : 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="container"> <div class="header"><span>expand</span> </div> <div class="content"> <ul> <li>i'm putting search bar here.</li> </ul> </div> </div>
$(".header").click(function() { $('.content').slidetoggle().toggleclass('active'); if ($('.content').hasclass('active')) { $('.header span').text('collapse'); } else { $('.header span').text('expand'); } }); $('button').click(function(){ $(".header").trigger('click'); })
.container { width:100%; border:1px solid #d3d3d3; } .container div { width:100%; } .container .header { background-color:#d3d3d3; padding: 2px; cursor: pointer; font-weight: bold; } .container .content { display: none; padding : 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="container"> <div class="header"><span>expand</span> </div> <div class="content"> <ul> <li>i'm putting search bar here.</li> </ul> </div> </div> <button>another click</button>
Comments
Post a Comment