Search code examples
javascriptmodal-dialogbootstrap-modalbootstrap-5

How to specify API objects in Bootstrap 5 modal?


I'cant get this straight, been on this for quite some time. Basically, I'm on this movie app and need a modal. So far I got to point to show each movie individually, show their poster, title and score.

Now, the idea is to press on title and modal will pop up with description ${overview}. Okay, it works, BUT! Modal only shows first object's description, no matter on which movie's title I press.

Once you remove a modal and add a <div>${overview}</div> it works, shows description of each movie correctly, but once I put it in modal - won't work.

I tried to play around with on click with that button, googled all around but can't find a solution. Any help or direction would be amazing, thank you!

Please see code here: https://github.com/sscip/movie-app-ms2


Solution

  • You need change data-bs-target to bind different button and modal.

      movies.forEach((movie) => {
        const {poster_path, title, vote_average, overview, uid} = movie; // Pulling necessary names from API
        console.log(overview)
    
        const movieBox = document.createElement("div"); //creating a div for individual movie elements
        movieBox.classList.add("movie"); // creating a class for it
    
        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 pulling information from API
    
        
    
        mainSection.appendChild(movieBox); // sending back to HTML file
      });
    

    varying-modal-content