Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score.

The goal is to have the modal show up with the movie's description when the title is clicked. However, I am facing an issue where the modal only displays the description of the first object, regardless of which movie's title I click on.

When I remove the modal and add

<div>${overview}</div>
, it successfully shows the description of each movie as expected. But, once I try to put it back in the modal, it stops working correctly.

I have tried various solutions such as adjusting the onclick function and conducting thorough research online, but still haven't found a resolution. Any guidance or assistance would be greatly appreciated, thank you!

You can view the code here: https://github.com/sscip/movie-app-ms2

Answer №1

Make sure to update the data-bs-target attribute to connect different buttons and modals.

  movies.forEach((movie) => {
    const {poster_path, title, vote_average, overview, uid} = movie; // Extracting essential data from API
    console.log(overview)

    const movieBox = document.createElement("div"); //creating a div for individual movie elements
    movieBox.classList.add("movie"); // adding a class for styling

    movieBox.innerHTML = `
      <div class="movie-image"><img src="${IMGPath + poster_path}" alt="${title}" /></div>
      <div class="movie-info">
        <button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#${uid}">
          ${title}
        </button>
        <span class="${classByRating(vote_average)}">${vote_average}</span>
        
        <div class="modal fade" id="${uid}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">${title}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                ${overview}
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    `; // creating markup for every movie element and extracting information from API

    

    mainSection.appendChild(movieBox); // displaying in HTML file
  });

varying-modal-content

Answer №2

It seems that you were missing a couple of key elements:

  1. The text color for the modal content
  2. A unique ID for each button and modal

Below is a solution that should work well: P.S: You can also view it on JSfiddle here.

// API link with key, please follow readme how to create own API key for application to work.

const APIKey = 'dontreallyneedit';
const APIURL = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=" + APIKey + "&page-1";
const IMGPath = "https://image.tmdb.org/t/p/w1280";
const SearchAPI = "https://api.themoviedb.org/3/search/movie?&api_key=" + APIKey + "&query=";
<!-- Other JavaScript code -->
@import url('https://fonts.googleapis.com/css2?family=Lato:wght@100;300&display=swap');
.modal-content {
  color: black;
}
/* Additional CSS styles */

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

Get a subsection of the array starting from index N up to the final

Is there a way to accomplish this specific transformation? ["a","b","c","d","e"] // => ["c", "d", "e"] I initially thought that using the slice method could work, however.. ["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ] ["a","b ...

Ng-show not updating when scope variable changes

Initially, I set the boolean flag of the infoWindow to false: $scope.infoWindow = false; Subsequently, I've added a google maps listener for a click event as shown below: google.maps.event.addListener(circle, 'click', function(event) { ...

The technique for handling intricate calls in node.js

My goal is to create a social community where users are rewarded for receiving upvotes or shares on their answers. Additionally, I want to send notifications to users whenever their answers receive some interaction. The process flow is detailed in the com ...

Top approach for triggering and re-triggering AJAX using php

I'm in the process of deciphering instructions from my developer. Our approach may not be entirely correct, so I want to ensure that we are on the right track. This is our objective: On a webpage, there exists a button. When this button is clicked, I ...

Executing a jQuery function automatically & Invoking a jQuery function using the onClick attribute in an HTML element

Having some issues with jQuery and could use some assistance... Currently, I am trying to have a jQuery function automatically execute when the page loads, as well as when a button is clicked. [Previous Issue] Previously, the jQuery function would automa ...

Updating columns in MongoDB using arrays in JavaScript has just gotten easier

When trying to update a mongoDB collection with an array value, the update fails without any error message. This method causes the issue: var arr = ["test","test1","test2"]; $.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , { ...

What sets apart the <script> tag with a type attribute from the standard <script> tag in HTML?

Similar Question: Is it necessary to include type=“text/javascript” in SCRIPT tags? While working on my HTML project, I noticed that the JavaScript code within script tags is evaluated even if the type attribute is not explicitly set to "j ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

Having trouble with loading image textures in three.js

Here is the code snippet I am using: var scene = new THREE.Scene(); // adding a camera var camera = new THREE.PerspectiveCamera(fov,window.innerWidth/window.innerHeight, 1, 2000); //camera.target = new THREE.Vector3(0, 0, 0); // setting up the renderer ...

Is the parent node of the input element the input element itself?

When working with a DOM object obj of type <input>, I encountered an issue where attempting to obtain its parent node using obj.parentNode resulted in the same obj being returned. Is this behavior specific to <input> objects? What other types o ...

Ajax encountered a problem while attempting to download the file

I have a situation where JavaScript generates content within a function, and I need to save that content in my downloads folder. However, when I attempt to do so via AJAX, it does not work and no errors are being displayed. Here is the JS code: $.ajax({ ...

Navigating through asynchronous transactions in Node.js: A Guide

My application utilizes Nodejs, Mongodb, and amqp. The main module receives messages from amqp, processes them by saving message information into mongodb within a message transaction, and executes additional logic. function messageReceiverCallback(msg) { ...

JQuery syntax for adding a comma before the first element in an array

When I insert data into an array, the output in my console includes a comma before the first element (9). How can I remove this comma from the first element using the provided code snippet? ,9,My firstname,My lastname,<a href="/cdn-cgi/l/email-protecti ...

Achieving cell merging in react-table can be accomplished by utilizing the appropriate

Currently, I am using react-table and have the need to combine cells in specific columns based on their content. Essentially, I want to remove the divider border between these merged cells. To give you a visual idea, this is how it currently looks like: h ...

Trigger a functional component's function in React using Chrome developer tools

function App() { const myFunction = () => { console.log('hello world!') } return <div>...</div> } After the website has fully loaded and the component is mounted, can we access the JavaScript to call myFunction()? ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

Issue with Global Variable Not Being Updated in Javascript

In my code snippet below, I am struggling to update a global variable within a callback function. function FunctionOne() { var result = ""; for (var i = 0; i < 10; i++) { AjaxFunction(function (data) { result += data; ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

Steps for creating an HTML report using Intern JS

Our team relies on intern JS for automating functional tests, however we are facing difficulty in generating an html report. I attempted to use locvhtml as suggested by the Intern documentation (https://theintern.github.io/intern/#reporter-lcov), but unfo ...