Leveraging the collapse feature within the info API on a bootstrap card

I am currently learning Full Stack development and working on a cryptocurrency project. The goal is to use AJAX to call crypto coin data from an API, search for specific cryptocurrencies, display the information on Bootstrap cards, and implement toggle switches with collapsible additional information from the API. However, I'm encountering an issue where the collapse functionality is not working as expected. I've tried various solutions and even spent two weeks searching on Google but haven't been able to figure out what's wrong with my code. Your help would be greatly appreciated!

Below is a snippet of my code:

let cryptos = []
const baseUrl = 'https://api.coingecko.com/api/v3/coins'
let singleCrypto = {}

// Functions for displaying all and searching for cryptocurrencies

When clicking on the "MORE INFO" button for "bitcoin," I should receive additional data from the moreInfo function. However, instead of getting the desired information, I'm seeing the following error in the console:

Uncaught ReferenceError: bitcoin is not defined
    at HTMLButtonElement.onclick (home.html:1:15)
onclick @ home.html:1

Answer №1

Your code seems a bit complex, but I believe I have grasped the gist of what you are trying to achieve

let cryptoContainer=document.getElementById("cryptoContainer");
const baseUrl = 'https://api.coingecko.com/api/v3/coins';

function createCoinCard(crypto) {
   let cardDiv=document.createElement("div");//create single coin container
   cardDiv.innerHTML = `
      <div class="col-3">
      <div class="card" style="margin: 10px; border: 1px solid gray">
      <div class="card-body">
      <div id="toggle"></div>
        <h5 class="card-title">${crypto.name}</h5>
        <div class="symbolDV">
          ${crypto.symbol}
        </div>
        <button type="button" class="btn btn-primary" type="button" 
        data-bs-toggle="collapse" data-bs-target="#collapse" aria-expanded="false">MORE INFO </button>
        <div id="collapse"></div>
      </div>
    </div>
  </div>`;
return cardDiv;
}
function showMoreInfo(data,collapseSection) {  
  collapseSection.innerHTML = `
    <img src="${data.image ? data.image.thumb : ''}" alt="Card image cap">
    <div class="usd">${(data.market_data.current_price.usd) + 'USD'}</div>
    <div class="eur">${(data.market_data.current_price.eur) + 'EUR'}</div>
    <div class="ils">${(data.market_data.current_price.ils) + 'ILS'}</div>
      `
  console.log('moreInfo:', data)
}
function displayAllCrypto() {
  $.ajax({
    type: 'GET',
    datatype: 'json',
    url: baseUrl,
    success: function (data) {
      for(var i in data){
        let card=createCoinCard(data[i]);//create individual coin card       
        let button=card.querySelector("button");//locate the "MORE INFO" button
        button.dataPointer=data[i];//assign data pointer
        button.onclick=function(){//add event listener
          showMoreInfo(this.dataPointer,this.parentNode.querySelector("#collapse"))
        }
        cryptoContainer.appendChild(card);//add card to main container
      }
    },
    error: function (error) {
      console.log('error : ', error)
    },
  })
}
displayAllCrypto();

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

Using dot notation for event handlers in Vue.Js is a handy technique

I am currently developing a Single Page Application (SPA) using Vue.js 3 and Bootstrap 5. On the main page, I have implemented the Bootstrap Offcanvas element with code that closely resembles the one provided in the documentation. The structure of the off ...

The integration of Ajax with Codeigniter poses a challenge in calling functions

Within the Welcome controller method, there's a function called send_otp responsible for verifying and sending OTPs. Usually, upon clicking the submit button after entering a mobile number, the system should trigger an AJAX request to this function. ...

Troubleshooting: Issue with JQuery click functionality within Django's AJAX implementation

I've been tackling the Tango with Django exercises to get a better grip on Django. I'm almost finished, but I'm hitting a snag with the Ajax segment. The Ajax function for auto-adding a page isn't triggering. I can't seem to figur ...

Caution: It is important for every child within a list to possess a distinct "key" prop. What is the solution to this issue?

Lately, I've encountered an issue with my project. Previously, everything was working fine, but now I keep receiving an error that prevents my notes from showing up when I click on the "my notes" section. The backend is operational and I can see the s ...

Optimizing Chrome's Precious Load Time

Encountering issues with Chrome browser auto-filling passwords, usernames, etc. Creating a problem where input field validation for emptiness is not possible in Chrome while it functions correctly in other browsers. $(document).ready(function() { ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

Change the chart.js labels every time I make changes to the chart

I've been using chart.js to generate dynamic charts. While I can create different types of charts and manipulate the data displayed, I'm struggling with updating the labels. Below is my code snippet showcasing how I update the data: const color ...

Submitting an Ajax form with preventDefault functionality is a great way to

I am having issues with a normal HTML form that is supposed to prevent default form submission and post the values using Ajax. Unfortunately, it is not working with my current setup. I consider myself a novice in jQuery and JavaScript, so any help would be ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

Using jQuery to target nested HTML elements is a great way to efficiently manipulate

Within the code below, I have a complex HTML structure that is simplified: <div id="firstdiv" class="container"> <ul> <li id="4"> <a title="ID:4">Tree</a> <ul> <li id="005"> ...

Eliminating error messages that appear when a user clicks on a legend label

Within my Laravel 5.7 application, I am utilizing Chart.js version 2.7.2 for a Stacked Line chart feature that opens a modal dialog when a user clicks on points within the report. var lineCanvas = document.getElementById("canvasVotesByDays"); var ...

An alternative approach to ajaxSetup in AngularJS

I am currently working with AngularJS and have set up controller and service layers to handle all AJAX calls (such as GET, PUT, etc.). I've placed all API call functions (http GET, PUT...) in the service layer and am calling them from the controller. ...

What is the optimal approach for creating new objects using a mandatory module?

After dividing my code into several Typescript classes and interfaces, I realized that although this method is effective for testing and maintenance purposes, I am curious if there might be a better approach to constructing required objects. Currently, I h ...

Struggling to make $.ajax.mostRecentCall function properly in jasmine 2.0.2

Struggling to make a basic example work properly. I found this code snippet on https://gist.github.com/Madhuka/7854709 describe("Check for spies", function() { function callFunction(callbacks, configuration) { $.ajax({ url: configurat ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Incorporating multiple web services into a React JS project to populate a Material UI dropdown efficiently

I have some code that is calling a web service and I have a few questions. Firstly, what is the best way to call a second web service? Currently, I am calling one and displaying the data in a list. But if I need to call a second web service, should I also ...

Ways to acquire Json information from various websites

Imagine having a directory called /api/cat/fact.js. You want to fetch JSON Data from the website catfact.ninja The challenge is that you are unable to use the require() or request() package. If you try using require, it will display an error message say ...

Controlling the v-model value of a v-select within a v-for loop

I have set up a table of members using a v-for loop, and certain users have the ability to manage other members based on their role. I have implemented some checks to prevent unauthorized roles from intervening, but the full list of checks is carried out o ...