How to expand and collapse multiple divs, without repeating the same code using jQuery

css expand/collapse div example
data-toggle=collapse
bootstrap card expand
bootstrap table collapse
bootstrap 4 collapse animation
bootstrap accordion multiple open
bootstrap toggle
bootstrap 4 collapse table row

I want to write a code that expands and collapses a div with a paragraph, once you click the header text above it.

<div class="container">
<h3><span class="toggler">Text that toggles</span></h3>
<div class="wrapper">
<p>Random text</p>
</div>
</div>

 <div class="container">
<h3><span class="toggler2">Text that toggles</span></h3>
<div class="wrapper2">
<p>Random text</p>
</div>
</div>

I am aware that I could write a function like this which would toggle between display: block and display: none.

I could just repeat the same function for different divs with different classes and it would work, but if I have a lot of them I would end up repeating the same function multiple times and I feel like there has to be a much cleaner way to do this.

$(document).ready(function() {
$(".toggler").on("click", function() {
    $(".wrapper").toggleClass("active");
   });
});

You dont need to repeat it, give both a single class like "toggle-enabled" then instead of using toggler and toggler2 as two function you can put toggle-enabled as one selector and both will run the same function on click.

If you want to only toggle the one selected then use "this" keyword to get current and hide and show that or slide it whatever you want to do but dont need to repeat the code.

Here is your example code working as expected:

$(document).ready(function() {
 $(".toggle-enabled").on("click", function() {
   var nextdiv = $(this).parent().siblings("div");
   nextdiv.is(":visible")?nextdiv.hide():nextdiv.show();
 });
});
.togglethis{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3><span class="toggler toggle-enabled">Text A that toggles</span></h3>
<div class="wrapper togglethis">
<p>Random text</p>
</div>
</div>

 <div class="container">
<h3><span class="toggler2 toggle-enabled">Text B that toggles</span></h3>
<div class="wrapper2 togglethis">
<p>I have left your toggler2 class in there and you can add more classes to separate it</p>
</div>
</div>

Collapse, Useful for grouping great amount of texts and/or graphics into expanding and show and hide multiple elements by referencing them with a JQuery selector in its href or triggered another control element also tied to the same collapsible element). If the control element's HTML element is not a button (e.g., an <a> or <​div> )  These rows are initially hidden and can be shown by clicking on expand/collapse control . Child rows are also used by Responsive extension to display columns that do not fit the screen. Solution depends on whether you use Responsive extension for your table powered by jQuery DataTables. Expand/collapse all child rows in a regular table

You don't need write single line of code if you use jquery & bootstrap.

Solution 1:

Add reference bnelow:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

your html:

<div class="container">
    <h3><span class="toggler" data-toggle="collapse" data-target="#col1">Text that toggles</span></h3>
    <div class="wrapper" id="col1">
        <p>Random text</p>
    </div>
</div>

<div class="container">
    <h3><span class="toggler2" data-toggle="collapse" data-target="#col2">Text that toggles</span></h3>
    <div class="wrapper2" id="col2">
        <p>Random text</p>
    </div>
</div>

Solution 2:

Either you can write simple line code

$(document).ready(function() {
 $("h3").on("click", function() {
    $(this).next().toggleClass("active");
 });
});

we can select header with header Tag. After that, we can add toogleClass to just next element that is "DIV".

so, when click header, toggleClass will be added to next element that is DIV

Jquery simple expand collapse div, Here I write the code to expand and collapse all panels using jQuery. Typically, I would assign an ID to each div and also the same class, Aug 15, 2019 · This code of auto collapse accordion works with jQuery without bootstrap. JQuery and Jul 20, 2012 · Anyone have an idea of how to do this with multiple div tags? Multiple targets A <button> or <a> can show and hide multiple elements by referencing them with a JQuery selector in its href or data-target attribute. Multiple uses of <button> or <a> can show and hide an element if they each reference it with their href or data-target attributes.

This code should work for your html:

$(document).ready(function () { 
    $('[class^="toggler"]').on('click', function () { 
        $(this).closest('.container').children('[class^="wrapper"]').toggle();
     });
});

The code looks for any element on your html whose class name starts with toggle. It then attaches an on-click handler function. That function then looks for the affected element's closest ancestor with class name of container. Then from that ancestor/parent, it selects children with class name starting with wrapper. It then toggles the visibility of those children (or child)

You could give your togglers class names of toggleN (where N is any valid class name character) or simply toggle (same class name for all). Similarity, you could name the classes for your wrappers as wrapperN or simply wrapper.

.toggle(), CLA · Style Guides · Bug Triage · Code · Documentation · Web Sites Description: Bind two or more handlers to the matched elements, to be The .​toggle() method binds a handler for the click event, so the rules outlined for For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Learn how to create a collapsible section. Click the button to toggle between showing and hiding the collapsible content. Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna

jQuery.data(), Store arbitrary data associated with the specified element and/or return the The jQuery.data() method allows us to attach data of any type to DOM elements in corresponding data for "name", and is therefore the same as jQuery.data( el, "​name" ) so do not assume that it contains only data that your own code has stored. Collapsible widgets are a popular way to create sections of content that can contract and expand. There are a ton of different implementations out there. Here, thanks to checkbox input elements, label elements and the :checked pseudo-selector, we’ll be able create such widget without the need for extra JavaScript.

Simple jQuery Accordion, jQuery Make sure either to run on DOM ready or at the bottom of the page. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. These related posts were algorithmically generated and displayed here without any load on my server at all​, I added in some lines of code, but now when I click on a div, the  Just add data-toggle="collapse" and a data-target to element to automatically assign control of a collapsible element. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element. If you'd like it to default open, add the additional class in.

Swapping Out Text, Five Different Ways, It's a common need in web apps: you click something and the text of the thing you just button that swaps to “Hide”, or “Expand Description” to “Collapse Description. of using too much jQuery around here for things that can be done without it. elements with default browser styling take well to pseudo element so let's use  Bootstrap 4 has built-in classes and JS plug-in that you may use to accomplish this task. In the next section, you can see live examples of using Bootstrap collapse related classes in action with complete code. An example of collapse/expand content via links in card (panels) In the first example of using collapse component, I have used two

Comments
  • stackoverflow.com/questions/17460116/…
  • Use $("[class^='toggler'") as first selector and $(this).find(".wrapper") as second
  • The [attribute^=value] selector selects all elements with a title attribute value starting with value, you need to apply $("[class^='toggler'").on("click", function(){ $(this).next(".wrapper").toggleClass("active"); }); in order to open all .wrapper in above code.
  • Vikintas Raudavicius did you checked my answer
  • I have added parent to get to h3 from span but you can choose any selector to get to next div within that container or you can place a class on container to select that. The benefit of having a indexed selector is speed in finding it then traversing and searching.
  • Why are you adding bootstrap? It has nothing to do with what the OP is askng.
  • you know class="container" is bootstrap class that's why adding.