简体   繁体   中英

jQuery slideToggle Multiple Divs At One Time

Here's my code,

 $(document).ready(function (e) { $('.showhide').click(function(e) { $(this).nextAll('.dropdown:lt(1)').slideToggle(100); e.stopPropagation(); }); $(window).click(function(e) { var container = $(".dropdown"); if (container.is(':visible') && !$(e.target).closest('.dropdown').length) { container.hide(); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="showhide">Button</a> <div class="dropdown"> <a href="#">Update</a> <a href="#">Delete</a> </div> <a class="showhide">Button</a> <div class="dropdown"> <a href="#">Update</a> <a href="#">Delete</a> </div>

This code is Opening & Closing the divs fine. Also, if I click outside while div is open it's closing them fine.

But, problem is that it's opening multiple divs at one time if I click them one after other. How can I open only one div at one time?

You can hide siblings when you click on any showhide element.

 $('.dropdown').hide() $('.showhide').click(function(e) { e.stopPropagation(); $(this).siblings('.showhide').next('.dropdown').slideUp() $(this).next('.dropdown').slideToggle(100); }); $(window).click(function(e) { var container = $(".dropdown"); if (container.is(':visible') && !$(e.target).closest('.dropdown').length) { container.hide(); } });
 a.showhide { display: block; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="showhide">Button</a> <div class="dropdown"> <a href="#">Update</a> <a href="#">Delete</a> </div> <a class="showhide">Button</a> <div class="dropdown"> <a href="#">Update</a> <a href="#">Delete</a> </div>

Try something like this

 $(document).ready(function (e) { $('.showhide').click(function(e) { el = $(this).nextAll('.dropdown:lt(1)') el.slideToggle(100); $('.dropdown').not(el).hide();//hide all execpt the current one e.stopPropagation(); }); $(window).click(function(e) { var container = $(".dropdown"); if (container.is(':visible') && !$(e.target).closest('.dropdown').length) { container.hide(); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="showhide">Button</a> <div class="dropdown"> <a href="#">Update</a> <a href="#">Delete</a> </div> <a class="showhide">Button</a> <div class="dropdown" style="display:none"> <a href="#">Update</a> <a href="#">Delete</a> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM