Having more than one bootstrap modal on a single page is not supported

I'm stuck and can't figure it out. I have multiple triggers that are very similar

<a style="margin: 4px 4px 4px 4px !important" 
   data-toggle="modal" 
   data-target="#video_modal" 
   data-title="YouTube video title" 
   data-youtube-url="YouTube/url/">Montenegro protesters decry opposition's use of Serbian symbols
</a>

<a style="margin: 4px 4px 4px 4px !important" 
   data-toggle="modal" 
   data-target="#audio_modal" 
   data-title="Soundcloud item title" 
   data-soundcloud-url="soundcloud/url">Katarina Panic: Montenegro elections-The real winners are citizens
</a>

The modal setups are below:

<div class="modal fade bd-example-modal-lg" id="video_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item youtube-iframe" src=""></iframe>
      </div>
      <div class="modal-footer">
      </div>
    </div>
  </div>
</div>


<div class="modal fade" id="submission-modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
         <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item soundcloud-iframe" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

And the JavaScript functions for those modals.

//SOUNDCLOUD MODAL SCRIPT
$('#audio_modal').on('show.bs.modal', function (event) {
  var source = $(event.relatedTarget); // Button that triggered the modal
  console.log(source + "Audio Modal JS");
  var title = source.data('title');
  var soundcloudurl = source.data('soundcloud-url'); 

  var iframeLink = soundcloudurl.replace(soundcloudrurl, 'https://w.soundcloud.com/player/?url=$1');

  var modal = $(this);
  modal.find('.modal-title').text(title);
  modal.find('.audio-iframe').attr("src",iframeLink);

})

//YOUTUBE MODAL SCRIPT
$('#video_modal').on('show.bs.modal', function (event) {
  var source= $(event.relatedTarget); 
  console.log(source + "Video Modal JS");
  var title = source.data('title');
  var youtube_url = source.data('youtube-url'); 

  var iframeLink = youtube_url.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, 'www.youtube.com/embed/$1');

  var modal = $(this);
  modal.find('.modal-title').text(title);
  modal.find('.youtube-iframe').attr("src",iframeLink);

})

Oddly enough, the YouTube modal works perfectly fine, but the sound-cloud modal doesn't appear at all.

I'm certain that my classes and IDs are correct because the YouTube modal is functioning. There must be something else I'm missing. Any suggestions?

Answer №1

Having two separate modals on your page is unnecessary. I have refactored the code to consolidate everything into a single modal that can handle multiple scenarios.

You just need to assign an id to your a element and then use JavaScript to check which one triggered the modal by checking its attribute. Based on that, you can apply the appropriate data to the modal.

In general, having less code leads to more dynamic and efficient results.

See below for a live working example:

//SOUNDCLOUD MODAL SCRIPT
$('#myModal').on('show.bs.modal', function(event) {

  var modal = $(this)
  var button = $(event.relatedTarget) // Button that triggered the modal  

  if (button.attr('id') == 'soundcloud') {
    var title = button.data('title');
    var soundcloudurl = button.data('soundcloud-url'); // Extract info from data-* attributes
    //MODIFY THE SOUNDCLOUD URL TO INCLUDE THE EMBED PART OF THE URL STRING
    var iframeLink = soundcloudurl.replace(soundcloudurl, 'https://w.soundcloud.com/player/?url=$1');

    //SET THE TEXT AND THE SRC ATTRIBUTE OF THE MODAL
    modal.find('.modal-title').text(title);
    modal.find('.iframe').attr("src", iframeLink);
  } else {
    var title = button.data('title');
    var youtube_url = button.data('youtube-url'); // Extract info from data-* attributes

    //MODIFY THE YOUTUBE URL TO INCLUDE THE EMBED PART OF THE URL STRING
    var iframeLink = youtube_url.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, 'www.youtube.com/embed/$1');

    //SET THE TEXT AND THE SRC ATTRIBUTE OF THE MODAL
    modal.find('.modal-title').text(title);
    modal.find('.iframe').attr("src", iframeLink);
  }
})
#youtube {
  background: green;
  cursor: pointer;
}

#soundcloud {
  background: Yellow;
  cursor: pointer;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<a id="youtube" style="margin: 4px 4px 4px 4px !important" data-toggle="modal" data-target="#myModal" data-title="YouTube video title" data-youtube-url="YouTube/url/">Youtube
</a>
<br>
<a id="soundcloud" style="margin: 4px 4px 4px 4px !important" data-toggle="modal" data-target="#myModal" data-title="Soundcloud item title" data-soundcloud-url="soundcloud/url">Sound Cloud
</a>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel1"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item iframe" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №2

After running your code in my local environment, I discovered a couple of issues that needed to be addressed. Firstly, the id value of the second modal should have been "audio_modal" instead of "submission-modal," as depicted in the following image https://i.sstatic.net/DR711.png

Secondly, there was a minor typo with "soundcloudrurl," which should have actually been spelled as "soundcloudurl" https://i.sstatic.net/gbKcF.png

Below is the complete corrected code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <title>Document</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"></script>
  <script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
  <a style="margin: 4px 4px 4px 4px !important" 
   data-toggle="modal" 
   data-target="#video_modal" 
   data-title="YouTube video title" 
   data-youtube-url="YouTube/url/">Montenegro protesters decry opposition's use of Serbian symbols
</a>

<a style="margin: 4px 4px 4px 4px !important" 
   data-toggle="modal" 
   data-target="#audio_modal" 
   data-title="Soundcloud item title" 
   data-soundcloud-url="soundcloud/url">Katarina Panic: Montenegro elections-The real winners are citizens
</a>
   
<div class="modal fade bd-example-modal-lg" id="video_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item youtube-iframe" src=""></iframe>
      </div>
      <div class="modal-footer"></div>
    </div>
</div>
</div>
<div class="modal fade" id="audio_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
         <div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item soundcloud-iframe" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
<! -- Script for SoundCloud Modal -->
$('#audio_modal').on('show.bs.modal', function (event) {
  var source = $(event.relatedTarget); 
  console.log(source + "Audio Modal JS");
  var title = source.data('title');
  var soundcloudurl = source.data('soundcloud-url'); 

  // Modify the SoundCloud URL to include the embed part
  var iframeLink = soundcloudurl.replace(soundcloudurl, 'https://w.soundcloud.com/player/?url=$1');

  // Set text and SRC attribute of the modal
  var modal = $(this);
  modal.find('.modal-title').text(title);
  modal.find('.audio-iframe').attr("src",iframeLink);
});

// Script for YouTube Modal
$('#video_modal').on('show.bs.modal', function (event) {
  var source= $(event.relatedTarget); 
  console.log(source + "Video Modal JS");
  var title = source.data('title');
  var youtube_url = source.data('youtube-url'); 

  // Modify the YouTube URL
  var iframeLink = youtube_url.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, 'www.youtube.com/embed/$1');

  // Set the text and the SRC attribute of the modal
  var modal = $(this);
  modal.find('.modal-title').text(title);
  modal.find('.youtube-iframe').attr("src",iframeLink);

});
</script>
</body>
</html>

Thank you and have a wonderful day!

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

Exploring arrays to find the maximum sum of elements

Struggling to develop a Javascript function that identifies which element in an array of numbers (specifically phone numbers) has the highest sum? Despite feeling frustrated and defeated, I believe I am on the right track. Could someone provide some guidan ...

Having trouble retrieving the data associated with a specific ID from my datatable

I am looking to specifically load the UserData that belongs to the correct AdminId In this code snippet, all the UserData is loaded successfully. It's working fine. async mounted() { this.userData = (await DataService.index()).data; } Now, I wa ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

I'm looking to create an array of tags that contain various intersecting values within objectArray

Initially const array = [ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { grou ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

The error message "consts is not defined in React Carousel renderArrow" indicates

While working with the react-elastic-carousel package, I encountered an issue when attempting to implement my own custom arrows. This is the code snippet I used, which was borrowed from the documentation: function App() { return ( <div> ...

Tips for optimizing images for mobile screens and ensuring responsiveness

I'm trying to ensure that my image only loads on mobile screens and remains responsive so it doesn't stretch. However, the code I've written isn't working as expected. Currently, the image takes up the whole browser window and appears o ...

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Three fixed position divs arranged horizontally side by side

I am attempting to organize 3 divs in a row using Flex. ISSUE 1: The div that is centered is set with position: fixed. However, the two other divs on each side do not stay aligned with the centered fixed div when scrolling. If I change the centered div to ...

The current context does not have a reference to TextBox

I am encountering an issue with my simple aspx page. Despite not using Master Content Page, I am seeing the following error: The name 'txtFirstName' does not exist in the current context Here is my Markup: <%@ Page Language="C#" %> &l ...

Tips for ensuring that the callback method waits for the completion of Google Markers creation

While developing my app with the Google Maps library, I encountered an issue either due to an unexplainable delay in creating markers or an unseen asynchronous problem. Here is a breakdown of the situation: The code retrieves the locations of Electric Cha ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...

Step-by-step tutorial on designing an input slider to dynamically adjust the CSS :before linear-gradient values

Is there a way to achieve a gradient effect using pseudo-element :before on an image that can be customized by adjusting a slider input? I've been trying to implement this feature with the following code, but have not been successful so far. var ...

Is it feasible to implement hot swapping in Node.js?

Can Node.JS support or mimic hot swapping code functionality? If so, what is the process? Hot swapping, also known as hot plugging, involves replacing or adding components without system shutdown. Erlang and Lisp have native support for hot swapping. ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

Looking to iterate through MongoDB using a promise and a forEach loop? I'm aiming to populate an array

I've been struggling to iterate through elements in my MongoDB database and save the values to an array. Despite putting in hours of effort, I can't seem to get it done. Here's the code snippet: //shopController.js const Product = require ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

What is the best way to determine the number of lines within a textarea?

My goal is to accurately calculate the number of lines in a textarea, like so: line 1 line 2 line 3 line 4 which should equal 4 lines. Essentially, pressing enter once should create a new line. Unfortunately, the following code is not achieving this: v ...

How to retrieve values from a nested array in a Next.js application

I am diving into the world of nextjs and apollo for the first time, and I am currently facing a challenge with using .map to loop through database results. Below is the code for my component: import { gql, useQuery } from "@apollo/client" import ...