Issue with collapse functionality in Bootstrap not activating after using append()

Whenever the ajax call is successful, I am appending the content to the element with the id #special-contents. However, upon page load, the collapse button does not expand the panel. Below is my JavaScript code:

$.ajax({
        url: `${URL}/promotions/`,
        method: 'GET',
        dataType: 'json',
        success: function (response) {
            
            var promotions = response.promotions;

            var specialPromotions       = filterByCategory(promotions, 'special');

            for (var i = 0; i < specialPromotions.length; i++) {
                var specialPromotion = specialPromotions[i];

                // Append
                $('#special-contents').append(
                    `<div class="col-md-6">
                        <div class="panel">
                            <div class="promotionBox promotionBox1">
                                <div class="promotionImage">
                                    <img src="${specialPromotion.banner}">
                                </div>
                                <div class="promotionDesc promotionDesc1">
                                    <p>${specialPromotion.title}</p>
                                    <button data-category="Special" class="promotion-details btnShadow" type="button" data-toggle="collapse" data-target="special-${specialPromotion.id}" aria-expanded="false">
                                        View Details
                                    </button>
                                    <a href="${specialPromotion.btn_link}" class="btnShadow"
                                                        target="_blank">Visit</a>
                                    <div id="special-${specialPromotion.id}" class="panel-collapse collapse ">
                                        <div class="panel-body">
                                            <div class="promotionDetailsContent">
                                                ${specialPromotion.content}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>`
                );
            }
            
        },
        error: function (error) {
            console.error('Error fetching promotions:', error);
        }
    });

It should be noted that when I added it directly to the #special-contents element (static content), the collapse feature works as intended.

Answer №1

Here's a solution to the problem - store the element in a variable and refresh the bootstrap collapse.

for (var i = 0; i < specialPromotions.length; i++) {
                    var specialPromotion = specialPromotions[i];

                    var visitBtn = specialPromotion.btn_link ? `<a href="${specialPromotion.btn_link}" class="btnShadow" target="_blank">Visit</a>` : '';
                    
                    // Add
                    var newElement = $(
                        `<div class="col-md-6">
                            <div class="panel">
                                <div class="promotionBox promotionBox1">
                                    <div class="promotionImage">
                                        <img src="${specialPromotion.banner}">
                                    </div>
                                    <div class="promotionDesc promotionDesc1">
                                        <p>${specialPromotion.title}</p>
                                        <button data-category="Special" class="promotion-details btnShadow" type="button" data-toggle="collapse" data-target="#special-${specialPromotion.id}" aria-expanded="false">
                                            View Details
                                        </button>
                                        ${visitBtn}
                                        <div id="special-${specialPromotion.id}" class="panel-collapse collapse">
                                            <div class="panel-body">
                                                <div class="promotionDetailsContent">
                                                    ${specialPromotion.content}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>`
                    );

                    $('#special-contents').append(newElement);
                }

                newElement.find('[data-toggle="collapse"]').collapse();

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

What could be preventing a successful POST request with data when making an ajax call?

My goal is to send data using a POST request in client-side code. However, when the request reaches the controller methods, I am unable to retrieve the sent data. Here is the client-side code snippet: function AddUser() { var user = { ...

Concealing external scripts on specific webpages

In my HTML template, I have integrated a third-party JavaScript code that provides a chat option. This script is included in my header.html so that it appears on all pages. However, I do not want this chat option to display on the login page. I want it to ...

The canvas texture is not properly aligning with the SphereMesh

I have been experimenting with THREE.js and recently tried using a <canvas> element as a THREE.Texture. After finally successfully mapping the object to the mesh, I noticed that the texture was not wrapping around the SphereGeometry as expected; inst ...

I struggle to grasp the significance of the scene's positioning

I've been experimenting with some sample code using three.js, where I've created a plane and I want it to rotate around. Here's a snippet of my code: This is the setup for my camera: var camera = new THREE.PerspectiveCamera(70, window.inner ...

What is causing the div element to act as a container?

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7fafae1e6e1e7f4e5d5a1bba3bba5">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-B0v ...

Using HTML, jQuery, and JSON with an AJAX call to populate two web tables stacked on top of each other

I am encountering an issue with populating two tables using two searches based on user input in mySQL-JSON-AJAX. When the user enters a search term and clicks the corresponding button, data should populate the respective table. The problem arises when clic ...

Achieving both positive and negative styling in AngularJS with ng-class: A guide

I'm currently working on an application that requires indicating red for negative values and blue for positive values in a calculation. <td class="amount debit"> <input type="text" class="form-control" ng-model="vm.model.form.amount_debi ...

Issue with jQuery .ajax() not triggering success callback function when using JSONP

My Facebook iframe application is attempting to make a cross-domain request to my server for JSONP data. The client-side code I am using is as follows: jQuery.ajax({ url: '***', type: 'post', ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. ...

The function this.$set is failing to update an array in VueJS

I am facing an issue where the console log shows me the updated array xyz, but when I try to print it in the DOM using {{xyz}}, it does not update. Can anyone shed some light on why this might be happening? data() { return { xyz: [] } }, met ...

Calculating distinct values within a single key in an object

My goal is to track the occurrences of four specific string values within the same key. The issue lies in my struggle with adding multiple counters. While the first counter successfully tracks the initial condition, subsequent conditions within the if/els ...

Firebug version 2.0.1 has been triggered to break on previous breakpoints

Despite adding and removing breakpoints, Firebug continues to stop at the old breakpoints upon refreshing the page. I attempted solutions such as resetting all Firebug options and deleting the breakpoints.json file, but they have not resolved the issue. ...

Tips for transforming list items into an array of strings

let typeList="[Product,Task,Invoice,Media,Store]"; I need to transform the string above into an array like this:- let typeList=["Product","Task","Invoice","Media","Store"]; Any help with this is greatly appreciated. ...

Guide to attaching click and keydown events to an input field using Vanilla JavaScript

I am currently working on a project for freecodecamp where I have successfully created a functional example. However, there are a few things that I'm struggling to figure out. Firstly, I need help with executing an AJAX request by either typing in th ...

I am in search of a regular expression to validate a Jordanian phone number, whether it includes the country code or not

Looking for a regex pattern that can validate phone numbers beginning with either 0096279, 0096278, 0096277, or 079, 078, 077. ...

React is unable to identify the `initialValue` attribute on a DOM element

Warning: React is not able to recognize the `initialValue` property on a DOM element. If you intended for it to show up in the DOM as a custom attribute, use `initialvalue` in lowercase instead. If it was mistakenly passed from a parent component, make sur ...

The time selector does not appear in the v-date-picker widget

I need help figuring out how to select a time range using v-date-picker on vCalender within my Vuetify project. Despite setting the mode of v-date-picker to dateTime, I am unable to find an option to choose the time along with the date. Is there something ...

Utilizing Bootstrap 4 to create fixed and fluid width side-by-side divs with scrollbars

I want to create a basic dashboard page. I decided to arrange two divs next to each other to serve as the side menu and content. Here is what the layout looks like: https://i.sstatic.net/EATK6.png I encountered an issue where the vertical scrollbar is n ...

Developing a progress bar with jQuery and Cascading Style Sheets (

Below is the code I'm currently using: <progress id="amount" value="0" max="100"></progress> Here is the JavaScript snippet I have implemented: <script> for (var i = 0; i < 240; i++) { setTimeout(function () { // this repre ...

What could be causing my resize event to not trigger?

My goal is for the #sequence div to be full height of the browser window when the window size is greater than 920px in height. In such cases, I also want to trigger a plugin. If the window size is lower than 920px, then the height of the #sequence div shou ...