Expandable and retractable container - reveal or hide content

I am in the process of developing a Frequently Asked Questions webpage that includes around 50 questions. To avoid making the page too long, I have decided to implement collapsible divs. Below is the code snippet that I have already implemented.

My query is whether it is possible to include a hyperlink (e.g. /#question20) that can direct users to a specific div which automatically expands when clicked on the hyperlink?

Additionally, what would be the most effective method for adding expand all/collapse all buttons?

<div class="panel-group" style="width: 70%; float: right; min-width: 300px;">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title"><strong><a href="#collapse1" data-toggle="collapse">Question 1</a></strong></h3>
        </div>
        <div id="collapse1" class="panel-collapse collapse">
            <div class="panel-body">Answer 1</div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title"><strong><a href="#collapse2" data-toggle="collapse">Question 2</a></strong></h3>
        </div>
        <div id="collapse2" class="panel-collapse collapse">
            <div class="panel-body">Answer 2</div>
        </div>
    </div>

Answer №1

Utilizing only HTML, you have the option to utilize the <details> and <summary> tags. If you prefer to incorporate JavaScript, you will need to create a tag and attach a load event listener to it.

Within the function linked to that listener, you can toggle a class named hidden or directly modify the style, such as altering the style with a fresh class labeled hidden for the divs that are expandable and concealable:

Revamp your HTML by introducing a new class to the hidden div:

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title"><strong><a href="#collapse1" data-toggle="collapse">Question 1</a></strong></h3>
    </div>
    <div id="collapse1" class="panel-collapse collapse hidden">
        <div class="panel-body">Answer 1</div>
    </div>
</div>

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title"><strong><a href="#collapse2" data-toggle="collapse">Question 2</a></strong></h3>
    </div>
    <div id="collapse2" class="panel-collapse collapse hidden">
        <div class="panel-body">Answer 2</div>
    </div>
</div>

Introduce a fresh CSS rule:

.hidden {
            display: none;
}

Lastly, include the JavaScript snippet:

<script>
        document.addEventListener('DOMContentLoaded',function() {
            var expandLinks = document.querySelectorAll('.panel-heading .panel-title a ');

            for(var i = 0; i < expandLinks.length; i++) {
                expandLinks[i].addEventListener('click', function(event) {
                    console.log(event.currentTarget);
                    var selector = event.currentTarget.getAttribute("href");
                    var answersDiv = document.querySelector(selector);
                    answersDiv.classList.toggle('hidden');
                });
            }
        });
</script>

Answer №2

You can achieve the desired effect without using any JavaScript, simply by utilizing the CSS :target selector.
This feature allows the element to expand when someone accesses your page with a specific URI like yourwebsite.com/qa.php#collapse2

.panel-collapse { display: none; }
.panel-collapse:target { display: block; }
<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title"><strong><a href="#collapse1" data-toggle="collapse">Question 1</a></strong></h3>
  </div>
  <div id="collapse1" class="panel-collapse collapse">
    <div class="panel-body">Answer 1</div>
  </div>
</div>
<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title"><strong><a href="#collapse2" data-toggle="collapse">Question 2</a></strong></h3>
  </div>
  <div id="collapse2" class="panel-collapse collapse">
    <div class="panel-body">Answer 2</div>
  </div>
</div>

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

Choose a Range of DOM Elements

My challenge is to select a range of DOM elements, starting from element until element. This can be done in jQuery like this: (Source) $('#id').nextUntil('#id2').andSelf().add('#id2') I want to achieve the same using JavaScr ...

Select elements to apply styles to all child elements except the initial one

In the following HTML snippet, we have a div#parent with multiple child elements: <div id="parent"> <div id="ch1"></div> <div id="ch2"></div> <div id="ch3"></div> .... <div id="ch1234">&l ...

What is the correct way to embed a script tag within a block of JavaScript code?

I'm currently working on a JavaScript code that needs to be executed inside an iframe. The goal is to insert a script tag within the JavaScript code and then append it to the parent body of the iframe. Below is the snippet of my code attempting to ach ...

How to retrieve the row index from a table using JavaScript

This question has cropped up numerous times, and despite trying various solutions suggested before, none of them seem to be effective in my case. Within a modal, I have a table where users can make changes that are then used to update the database. The ta ...

What is the best way to change the height of a div element as the user scrolls using JavaScript exclusively?

Coding with JavaScript var changeHeight = () => { let flag = 0; while(flag != 1) { size += 1; return size; } if(size == window.innerHeight/2){ flag == 1; } } var size = 5; document.body.style.height = &qu ...

How to conceal table cells on Safari 5?

My code works on Firefox and IE, but not on Safari. Here's an example: <table> <thead> <tr> <th style="display: none;">hi</th> </tr> </thead> <tr class="someClass"> <td style= ...

Is there a way to display a button and text upon hovering over an image without using JQuery?

On my current WordPress project, I am faced with the task of creating a gallery that displays text and a button when users hover over an image. I have attempted to use a:hover but have only been able to make limited modifications. Can anyone provide guid ...

Why does "height: auto;" not function properly when I implement "float:left"?

I have set up three responsive columns and now I want to add a wrapping div for them. Although I have created the wrap div, it seems to only work with pixel values. I would prefer to use percentages or auto as I am aiming for a responsive layout. For exa ...

Struggling with CSS button hover effect: can't get border and background change to work

Hello coding community! I am a beginner in programming and I'm eager to learn. Recently, I came across a stunning button effect on Codepen that caught my attention. You can check it out here. However, when I tried to replicate the code from this exam ...

Looking to retrieve just your Twitter follower count using JavaScript and the Twitter API V1.1?

I am trying to retrieve my Twitter follower count using JavaScript/jQuery in the script.js file and then passing that value to the index.html file for display on a local HTML web page. I will not be hosting these files online. I have spent weeks searching ...

Grouping Columns in an HTML Table using Angular 4

I'm currently faced with the task of retrieving flat data from an API and presenting it in an HTML table using Angular 4. I'm a bit unsure about how to iterate over the data, possibly using a for-each loop. I have attempted to utilize ngFor but I ...

Error message: Selenium is having trouble finding the search bar, regardless of the selector method (such as xpath, css_selector, fullXpath, etc.)

My attempt to automate the search process on Facebook has hit a roadblock. I have tried the following code: search = driver.find_element_by_xpath('//*[@id="mount_0_0_ij"]/div/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div/label/input') ...

Tips for enabling a flexbox item to extend beyond its container

While attempting to utilize flexbox for creating a navbar with the logo in the center, I encountered an issue where the logo wasn't able to overflow from above and below the navbar. I experimented with squeezing in and positioning the element, but it ...

Expand a section of the webpage to fill the entire screen

I'm working with some HTML code that looks like this: <header>title</header> <content class="container-fluid"> <div class="row"> <div class="col-sm-3 leftside"> <ul> <li>test</li> ...

AngularJS incorporating dynamic stylesheets

I am facing a challenge with my AngularJS application as it fetches data via an API and dynamically builds a webpage. Typically, I rely on ng-style for dynamic styling, but now I need to utilize the nth-of-type attribute which can only be applied in a CSS ...

Exploring the dynamic world through HTML5 canvas and animated objects

Today I am exploring HTML 5 canvas and experimenting with moving 3 circles on the canvas. Based on my research, it looks like I need to continuously redraw the circles (perhaps every 60 milliseconds) and clear out the old circle before rendering the new on ...

`Hovering over a div triggers a continuous animation loop`

I've gone through various questions and solutions related to this issue, but unfortunately, none of them seem to work for me. It's possible that I might be overlooking something or my scenario is slightly unique. The main problem I'm facing ...

Detecting when users stop scrolling in Angular 5

Is there a way to toggle visibility of a div based on user scrolling behavior? I'd like the div to hide when the user scrolls and reappear once they stop. I've attempted to achieve this effect using @HostListener, but it only seems to trigger wh ...

Is there a quick way to apply the !important rule to all properties in a CSS file?

Seeking a quick one-line shortcut to add !important to every CSS property in my extensive CSS file. Any suggestions on making the whole .css file !important? ...

Creating a simulated textarea with a scrollbar and dynamically refreshing the content

Due to limitations on markup content inside <p> tags, I have decided to create my own custom textbox. This textbox will function as a console where the battle progress is logged. Initially, I attempted using nested divs for each log, but encountered ...