Is there a way to incorporate a bootstrap collapse feature into the dynamically generated cards on this page?

Recently, I've been experimenting with symfony and have successfully generated cards containing FAQ questions and answers. My current challenge is adding a collapse function to these cards. How can I achieve this?

I considered implementing an accordion collapse but haven't found a suitable solution online. If anyone has any tips on how to add a collapse feature to these generated cards, I would greatly appreciate it.

I believe the provided code includes everything necessary, but please let me know if additional information is required.

Any assistance will be highly valued!

{% extends 'base.html.twig' %}

{% block scripts %}
    {{ parent() }}
    <script>
        var counter = 0;
        const content = document.getElementById('content');
        $(document).ready(function() {
        $.ajax({
            url: "http://127.0.0.1:8000/api/faq"
        }).then(function(data) {
            data.forEach(FAQ => {
                counter++;
                const card = document.createElement('div');
                card.setAttribute('class','card');
                const question = document.createElement('h3');
                question.setAttribute('id','question'+counter);
                const answer = document.createElement('p');
                answer.setAttribute('id', 'answer'+counter);

                content.appendChild(card).className = "FAQCard";
                card.appendChild(question);
                card.appendChild(answer);


                $('#question'+counter).append(FAQ.question );
                $('#answer'+counter).append(FAQ.answer );

            })

        });

    });

</script>
{% endblock %}

{% block title %}
    Experience Manager
{% endblock %} 

{% block content %}
{% endblock %}

Answer №1

If you're utilizing Bootstrap 4, implementing a collapsible feature is a breeze.

Firstly, pinpoint the trigger and body sections of the card.

For instance, let's assume you have a button as the collapse trigger. This button should include the necessary data attributes such as data-toggle and data-target. Here's an example:

<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#demo">Simple collapsible</button>

The section that expands/collapses (body block) alongside the card requires an id and a matching class that align with the corresponding data-target and data-toggle set in the trigger above.

<div id="demo" class="collapse">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>

Here's an illustration, https://codepen.io/anjanasilva/pen/LXGEgK

To apply this dynamically,

Utilize

$(element).data('toggle', 'collapse');
and
$(element).data('target', '#ID');
for the triggers. For the body element, target it and add the class collapse, like so: $(element).addClass('collapse');.

I hope this proves helpful. Cheers!

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

How can I make Bootstrap fit my Custom Grid?

I have received specific measurements from a customer for a customized grid layout, and I am unsure of how to implement it. Here are the measurements provided: **Width: 320px** Sides: (26px) (2 sides) Column: (52px) (4 columns) Gutter: (20px) (3 gutter ...

Input only the necessary numeral

As someone who is just beginning to learn javascript, I am tasked with creating an input field that allows for the input of 'AND', 123, or (). I attempted using RegExp to achieve this. function requiredletter(inputtxt) { var letters =/&bso ...

Place a user input field within a div element having the specified class

I am trying to insert an HTML input element into the following div: <div class="sss" style="padding-top:2px"> <center> <input value="test1" name="name1" type="submit" > <input value="test2" name="name2" type="submit"> </c ...

Avoiding conflicts between banners, text, and images for HTML/CSS design

I'm having an issue with the banner I created for my project. It seems to be overlapping with text and images, hiding behind them. How can I fix this? Unfortunately, I can't post the link to my project here due to other files present. The specif ...

Leveraging the capabilities of the Freshdesk API

Has anyone had any experience utilizing the FRESHDESK API specifically for creating tickets? The documentation states the following: Request URL: domain_URL/helpdesk/tickets.xml Request method: POST <helpdesk_ticket> <description>Disk fai ...

What causes unexpected outcomes when using async / await with Array.map()?

Below is a functional version of my code that produces the expected output: ***.then(r => r.json()).then(async r => { for (let i = 0; i < r.length; i++) { let pipeline = r[i]; p ...

The dragging functionality in gridstack.js doesn't seem to be functioning correctly

I have been implementing GridStack.JS in the code snippet below (Basic Structure) <div class="grid grid-stack"> <div class="grid-item cards grid-stack-item" data-gs-width="4" data-gs-height="2"> <div class="inner-grid"> </div& ...

Launch a new window for a div when a button is clicked

Hey everyone, I need some help with opening a div in a new window. Currently, I am using window.open and it is working fine. Here is the code snippet: <div id="pass">pass this to the new window</div> <a href="#" onclick="openWin()">clic ...

Utilizing a child component in React to trigger a function on its sibling component

Trying to put this question into words is proving to be a challenge. I am wondering in React, if there is a way for a child component that is deeply nested (2 levels deep from the parent) to trigger a function on another component that it has a sibling rel ...

An error was encountered: object does not possess the function 'tooltip'

I have been attempting to display a tooltip on a textbox using jQuery scripts within a web form that utilizes a Master Page. While everything appears to be working fine when I run my code, I am encountering the above error in the resources folder of the DO ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...

Defining global 'require' scripts in Node.js

Seeking a solution to a slightly unusual problem. I hope that using simple examples will clarify my query, as explaining my complex usage can be challenging. I am incorporating my custom modules into the routes.coffee file for an Express server. My goal i ...

What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...

Tips for accessing and retrieving stored values within an array using JavaScript

I am trying to display stored values in an array one by one within an HTML table. The issue I'm facing is that currently, all values are being fetched at once. Can someone assist me in reading the values one by one? <script> var time=""; ...

Text color-coded for specific hues

I am looking to change the color of a specific text within HTML/PHP/CSS/JS code. Here is an example of the text structure: @john please move the invite to the next week. My goal is to make the word "@john" appear in green, while keeping the rest of the ...

Determining the position coordinates of an element in relation to the viewport using JavaScript, regardless of its relative positioning

I am currently developing a vueJs web application and I'm in need of determining the position of an element within my web app relative to the viewport itself, rather than its parent elements. I'm curious if there exists a function or property tha ...

Different Types of Buttons in HTML

As someone who is new to the world of HTML coding and JavaScript, I have a question about button types. According to the W3Schools website, there are three types of buttons: <button type="button|submit|reset"> First question: Why do we need a for ...

Utilize the qtip function in a loop using the .each method

I'm encountering an issue with implementing the Qtip jQuery plugin across a whole class of HTML elements: $(".peoplebtn").each(function() { $(this).qtip({ content: { text: $(this).attr('qTipText') } }); }); ...

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...