Ways to toggle the expansion and collapse of multiple divs efficiently with jQuery without duplicating code

I am trying to create a script that will expand and collapse a div containing a paragraph when the header text above it is clicked.

<div class="container">
<h3><span class="toggler">Click here to toggle text</span></h3>
<div class="wrapper">
<p>Random content</p>
</div>
</div>

 <div class="container">
<h3><span class="toggler2">Click here to toggle text</span></h3>
<div class="wrapper2">
<p>Random text</p>
</div>
</div>

I know I can use a function that toggles between display: block and display: none.

If I have multiple divs with different classes, repeating the same function for each one seems inefficient. There must be a more elegant solution.

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

Answer №1

By utilizing jquery and bootstrap, you can achieve your desired functionality without having to write a single line of code.

Solution 1:

To implement this solution, add the following references:

<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>

Update your HTML accordingly:

<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:

Alternatively, you can use this simple line of code:

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

This code snippet selects headers using the header Tag and adds toggleClass to the next adjacent element, which is a "DIV". As a result, clicking on the header will toggle the class of the subsequent DIV element.

Answer №2

Instead of repeating the code, assign both elements a single class like "toggle-enabled". Then, use this class as a selector for both elements to run the same function when clicked.

If you only want to toggle the currently selected element, use the "this" keyword to reference the current element and hide or show it accordingly without repeating the code.

See below for an example of how your code should work:

$(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>

Answer №3

To make this code function properly in your HTML document, follow these steps:

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

This script targets any element in your HTML with a class name that begins with toggle. It then adds an event listener for clicks on those elements. When clicked, the script finds the closest ancestor element with the class name of container. From there, it selects children elements with class names starting with wrapper and toggles their visibility.

You can name your toggle elements with class names like toggleN (where N is any valid character) or simply toggle. Similarly, you can name your wrapper elements with class names like wrapperN or just wrapper.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

We are experiencing difficulties rendering flash messages in Expressjs with Handlebars(hbs) and express-messages using flash-connect

I'm working on an express app and I want to display flash messages when a user signs up using a form. The technologies I am utilizing include Node.js, Express.js, Handlebars(hbs), connect-flash, and express-messages. To make finding errors easier, I ...

Tips for choosing an option from a react dropdown using Cypress

Exploring Cypress: I am currently working with the following code snippet. Although it seems to be functioning, I have a feeling that there might be a more efficient way to achieve the desired result. There are 25 similar dropdowns like this one on the pag ...

Adjust the sequence of the series in dimple's multi-series chart using interactive features

My latest project involves a unique dimple interactive chart featuring two series: a pie series and a line series based on the same dataset. You can view the chart at dimplejs.org/advanced_examples_viewer.html?id=advanced_interactive_legends Check out the ...

I possess 9 captivating visuals that gracefully unveil their larger counterparts upon being clicked. Curiously, this enchanting feature seems to encounter a perplexing issue within the realm of web browsing

<style type="text/javascript" src="jquery-1.11.0.min.js"></style> <style type="text/javascript" src="myCode.js"></style> </body> //jquery is within my site directory on my desktop $(document).ready(function(){ //note: $("#ar ...

Leveraging the power of Google Charts along with MySQL or

I've been working on this task for several days now and I'm still struggling to achieve the desired outcome. My goal is to dynamically create a column/bar chart using Google Charts, populated with data from my database. Here's my query: SE ...

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

Shut down two modal windows and then open one anew

I am facing an issue with fancybox where I need to open 2 modals of a plugin and then close 2 and open 1 again... For example: closing 2 modals and opening 1 modal again... http://jsfiddle.net/g3R75/1/ I have tried the following code but it doesn't ...

Creating a dynamic effect by applying a scale animation to a circle, overlaying centered text on top, and utilizing

I am attempting to create an animation for a button that consists of a black circle in the background and white text in the foreground. The black circle should scale from full size to smaller size, while the text should be white when overlapping the circle ...

Which core modules of Node Js serve as the foundation for Express Js?

Which core modules of Node.Js are utilized in the construction of the Express Js Framework? Besides the 'http' and 'fs' modules, what other modules does Express Js integrate? ...

What is the best way to send form data using AJAX with Braintree Transparent Redirect?

Utilizing Python and JQuery in this scenario... In the past, we relied on a standard form.submit(); within the submitHandler of the validation (JQuery plugin) call. The submission was made to Braintree's transparent redirect URL with the redirect-to ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

Refreshing Django HTML table dynamically upon database updates

Currently, I have an HTML table set up using a Django template to showcase data from my database. I am looking to ensure that this table remains updated in real-time whenever the database undergoes changes. Despite my research efforts, there is limited inf ...

react elements are consistently positioned at the bottom of the webpage

I am currently in the process of developing an airline reservation system using the MERN stack. I have successfully implemented the navbar, however, whenever I try to add a new div or element, it appears outside of the page and requires additional styling ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Clicking on a React Material UI ListItem

I am trying to develop a clickable country list with icons next to each ListItem. However, I am facing an issue where only one item can be selected at a time in a single click. Upon clicking a new item, the previously selected one gets deselected first. He ...

Superceding Meta Character Encoding Statements

Have you ever wondered what happens when two older-style character encoding declarations are used in a webpage? Will the first declaration override the second, or vice versa? Or will they both be ignored and excluded from the encoding algorithm? For Ex ...

Creating a way for a Node and React application to share classes

I am in the process of developing a Node and React application, both implemented using TypeScript. The directory structure of my project is illustrated below: https://i.sstatic.net/914A1.png My query: Given that I am utilizing the same programming langu ...

Is the .html page cached and accessible offline if not included in the service-worker.js file?

During the development of my PWA, I encountered an unexpected behavior with caching. I included a test .html page for testing purposes that was not supposed to be cached in the sw.js folder. Additionally, I added some external links for testing. However, w ...

Tips for displaying an array in a tabular layout using angularjs

API calls are my jam, and I'm trying to display the JSON results in a nice tabular format using angularjs. To achieve this, I've set up a function (myfunc) with a hardcoded array called train. Now all that's left is to print this array in a ...