Develop an interactive Bootstrap switch with JavaScript for a dynamic user experience

I have been exploring the potential of Bootstrap's collapse feature to implement a 'Show More' button on a webpage I am developing. The objective is to reveal more or hide the body text within a card description when the button is clicked.

The challenge arises from the fact that the content on the page is dynamically generated, creating uncertainty about how to integrate collapsible elements in this context. To make it work, I need to establish a connection between the button and the content that needs to be collapsed and expanded.

Although I consulted the Bootstrap documentation on handling collapsing elements, my attempts did not deliver the desired outcome likely due to the dynamic nature of my content creation process.

Here is an excerpt of the HTML:

<pre><code>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial- 
  scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link rel="stylesheet" href="carsStyling.css">

  <title>Weyland's Cars</title>
</head>
<body>
  <div class="row">
    <div class="col-md-4">
      <h1>Hello World</h1>
      <p>Welcome to Weyland's Cars</p>
    </div>
  </div>
  <div id="card-space" class="row">

  </div>

  <script src="cars.js"></script>
</body>
</html>

Furthermore, consider the JavaScript snippet below for generating car cards with collapsible text sections:

let cars = [];

function carCreator(make, model, colour, image, registrationNumber, price) {
  this.make = make;
  this.model = model;
  this.colour = colour;
  this.image = image;
  this.registrationNumber = registrationNumber;
  this.price = price;
  cars.push(this);
}

// Car instances
...

// Dynamically create card elements
cars.forEach(car => {
  // Card creation logic here
})

Answer №1

Your code is missing several crucial elements:

1: Ensure each 'content' has a unique identifier

2: Make sure to include the necessary references for the collapse feature to function correctly:
....a) Set details.className = 'body-text collapse';
... b) Set collapse.dataset.toggle = 'collapse'
...... Set collapse.setAttribute ('role', 'button')
...... Set collapse.setAttribute ('aria-expanded', 'false')
...... Set collapse.setAttribute ('aria-controls', 'body-text-area')

3: Include the following 3 JS libraries on the page!
... - jquery-3.2.1.slim.min.js
... - popper.min.js
... - bootstrap.min.js

If not, I couldn't make sense of your coding approach so I improvised it in my own way. Hopefully, this will be helpful.

class Cars {
  constructor(ref) {
    this.list = [];  // Do you really need a list?
    this.hmi_ref = ref;

    // Bootstrap: container type
    this.BS = {}
    this.BS.container = document.createElement('div');
    this.BS.card = document.createElement('div');
    this.BS.image = document.createElement('img');
    this.BS.info = document.createElement('div');
    this.BS.title = document.createElement('h4');
    this.BS.details = document.createElement('p');
    this.BS.collapse = document.createElement('a');

    this.BS.info.appendChild(this.BS.title)
    this.BS.info.appendChild(this.BS.details)
    this.BS.info.appendChild(this.BS.collapse);
    this.BS.card.appendChild(this.BS.image);
    this.BS.card.appendChild(this.BS.info);
    this.BS.container.appendChild(this.BS.card);

    this.BS.container.className = 'col-md-3';
    this.BS.card.className = 'card';
    this.BS.image.className = 'card-img-top';
    this.BS.title.className = 'card-title';
    this.BS.details.className = 'body-text collapse';
    this.BS.collapse.className = 'btn btn-primary';

    this.BS.collapse.dataset.toggle = 'collapse'
    this.BS.collapse.textContent = 'Show More'

    this.BS.collapse.setAttribute('role', 'button');
    this.BS.collapse.setAttribute('aria-expanded', 'false');
    this.BS.collapse.setAttribute('aria-controls', 'body-text-area');


  }
  add(make, model, colour, image, registrationNumber, price)
  {
    this.list.push({make, model, colour, image, registrationNumber, price}) // For list, but why?

    let carID = 'car_' + this.list.length;

    this.BS.image.src = image;
    this.BS.title.textContent = make;
    this.BS.details.id = carID;
    this.BS.details.innerHTML = `Model:${model}</br>Colour:${colour}</br>Registration:${registrationNumber}</br>Price:${price}`;
    this.BS.collapse.href = `#${carID}`;

    let newNode = this.BS.container.cloneNode(true)

    this.hmi_ref.appendChild(newNode);

    // return carID; ???
  }
}

const CardSpace = document.getElementById('card-space');

let myCars = new Cars(CardSpace);

myCars.add('Volkswagen', 'Polo', 'White', 'https://source.unsplash.com/random/1920x1080', 'ND 123 456', 'R125 000');
myCars.add('Chevrolet', 'Spark', 'Black', 'https://source.unsplash.com/random/1920x1080', 'ND 654 321', 'R112 000');
myCars.add('Renault', 'Clio', 'Red', 'https://source.unsplash.com/random/1920x1080', 'ND 456 789', 'R225 000');
myCars.add('Kia', 'Picanto', 'Grey', 'https://source.unsplash.com/random/1920x1080', 'ND 987 6546', 'R185 000');
myCars.add('Ford', 'Fiesta', 'Orange', 'https://source.unsplash.com/random/1920x1080', 'ND 123 987', 'R295 000');


// console.log(myCars.list)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<div class="row">
  <div class="col-md-4">
    <h1>Hello World</h1>
    <p>Welcome to Weyland's Cars</p>
  </div>
</div>
<div id="card-space" class="row"> </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

Implementing Image Upload Feature using Node.js and MongoDB

Can someone guide me on how to upload an image using node js? https://i.sstatic.net/xGpw7.png I've been attempting to upload a photo and store it in my database, but haven't had any success. Any advice on uploading photos to a database with no ...

Tips for ensuring a specific statement is only executed after the completion of an Async loop

Is there a way to ensure that the function FinalExecution is only run after all Async calls within the forEach function have been executed? runFunction=()=>{ cart.forEach(async(i)=>{ await axios.get(`localho ...

How can I populate a select dropdown list in Django using JsonResponse?

I've been working on displaying a list from my Django application in an HTML select option, but I'm having trouble getting it to show up. Also, I believe I need to assign IDs to the option values in the select list, but I'm not sure where to ...

Comparison between Bootstrap 4 and Firefox Preload Error

Hello fellow front end developers who are experiencing an issue with CSS preload in Firefox versions above 74.0. I have encountered a problem with the following code snippet: <link rel='preload' as='style' onload="this.onload=null; ...

Is there a way to solely adjust the color of a -box-shadow using jquery?

Looking for a way to incorporate tinycolor, a color manipulation framework, into setting a box-shadow color. Instead of directly setting the box-shadow with jQuery, you can use tinycolor on an existing color variable. $("CLASS").css("box-shadow", "VALUE") ...

Using identical CSS for two separate layouts

Imagine having to work with an html page that cannot be altered in any way. The only tool at your disposal is CSS. The page is loaded and shown through an iframe from a different domain. This particular page serves as a payment gateway, displaying either ...

Assigning the variable "name" attribute to an <input> element in HTML: A step-by-step guide

In the image below, I am working on creating a user interface using JSP and loops. I am looking to assign unique names to each input element to differentiate them. To achieve this, I plan to give them variable name attributes which I can set and populate ...

Bootstrap Cards Colliding with One Another

Can someone help me arrange 4 Bootstrap cards in a row, ensuring they are all the same width and height with some spacing between each card? Unfortunately, when viewing on a Tablet viewport, the cards end up overlapping. I attempted to use `col-md-3` so ...

nodejs - csvtojson returning incorrectly formatted JSON keys in output

I've been utilizing the csvtojson package in my nodejs project. Despite writing the code below to convert my csv file, I'm facing an issue where the keys in the generated json do not have double brackets. Consequently, I am unable to retrieve val ...

Modify the style of the list heading in CSS

I have a collection of items that are aligned to the left within their surrounding <div>. #list-container:before { content: 'The items:'; } #list-container span { display: block; } <div id="list-container"> <span>item1& ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

The Django static files were uncooperative and refused to function

I've encountered an issue with my HTML files while using Django. Some files work perfectly fine when I load static files, but others don't seem to cooperate. I'm perplexed as to why this inconsistency exists! Have I overlooked something impo ...

Issue with excessive content causing scrolling difficulty

I've created CSS for a modal dialog, but I'm facing an issue. When the content exceeds the vertical space of the wrapper, the scrolling functionality doesn't work correctly. Although I can scroll, it's limited and I can't reach th ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

When the action "X" was executed, reducer "Y" resulted in an undefined value

I'm encountering an issue with Redux in React. Despite searching through related questions, I haven't found a solution that fits my specific case. Here are the files involved: Index.JS import snackbarContentReducer from '../src/shared/red ...

Minimize the time displayed in a JavaScript DateTime string

The timetable data in the database is correctly formatted as: 2022-04-26T08:15:08.000Z However, when using node to select it, the time appears as: 2022-04-26T11:15:08.000Z I attempted to adjust the time on the front end using: hours.setHours(hours.getHou ...

How is it possible for TypeScript to permit an inaccurate comparison like boolean === undefined?

Encountering the peculiar behavior of TS. const isItLanding = false; if (isItLanding === undefined) { // valid return ...; } However, in this instance const isItLanding = 1; if (isItLanding === 'undefined') { // error return ...; } Why do ...

Pull content to the left using the pull-xs-left helper classes in Bootstrap 4

Is it supposed to work in theory? I'm attempting to float this box to the right on a row with 3 columns. What am I doing incorrectly here? Here is a pen: https://codepen.io/lucky500/pen/JbMMby <div class="container"> <div class="row"> ...

jquery-ui allowing to resize child divisions as well

Currently, I am in the process of developing a website that includes resizable divs with jQuery. However, I have encountered an issue where only the width of the child divs is being resized when I adjust them. For reference, you can view the site and its c ...

Fixed-positioned left column in a styled table

Struggling to implement the solution provided in this popular topic on Stack Overflow about creating an HTML table with a fixed left column and scrollable body. The issue arises from my use of the thead and tbody tags, which are not addressed in the exampl ...