Guide on developing a JavaScript script for implementing across numerous Bootstrap modals within a single webpage

I have been working on setting up a page with 14 different modals. Initially, all the modals were opening normally, but I recently discovered a way to make them draggable when opened. After some trial and error, I managed to implement this feature successfully for one modal. However, now I am facing an issue where only one modal opens while the rest do not unless I specifically reference their names in the code. This means that the first modal stops working if I change the code to accommodate another modal. Can someone please guide me on how to write JavaScript code that can be generalized for all my modals?

Below is the snippet of script code I am using:

<script type="text/javascript">
window.onload=function(){

$('#btn1').click(function() {
  // reset modal if it isn't visible
  if (!($('.modal.in').length)) {
    $('.modal-dialog').css({
      top: 110,
      left: 500
    });
  }
  $('#modal1').modal({
    backdrop: true,
    show: true
  });

  $('.modal-dialog').draggable({
    handle: ".modal-header"
  });
});


    }

</script>

And here are excerpts from my modals' code (for two modals instead of all 14):

<button id="btn1" class="btn btn-info btn-lg" data-target="#modal1">Modal     1</button>

<div class="modal fade" id="modal1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button class="close" data-dismiss="modal" aria-label="Close"><span     aria-hidden="true">×</span></button>
        <h4 class="modal-title" >Modal 1</h4>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
      </div>
    </div>
  </div>
</div>

<div class="container">
<button id="btn2" class="btn btn-info btn-lg" data-target="#modal2">Modal 2</button>

<div class="modal fade" id="modal2" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button class="close" data-dismiss="modal" aria-label="Close"><span     aria-hidden="true">×</span></button>
        <h4 class="modal-title" >Modal 2</h4>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
      </div>
    </div>
  </div>
</div>

Adding another script after the existing one with new "#btn" or "#modal" results in only the latest one working. When adding a comma after the first "btn" or "modal", the two modals end up overlapping. What could be causing this issue? Any help would be greatly appreciated.

Answer №1

If you're looking to streamline the process of setting up modals without extensive JavaScript configuration, one approach could be utilizing HTML data attributes for toggling. This way, you would only need to focus on initializing your draggable functionality.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Brief page description within 150 characters">    
<title>Modals</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style>
</style>
</head>
<body>
      <div class="modal fade" id="modal1" tabindex="-1" role="dialog" aria-labelledby="modal1Label" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="modal1Label">Modal title</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              Modal 1
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Save changes</button>
            </div>
          </div>
        </div>
      </div>

      <div class="modal fade" id="modal2" tabindex="-1" role="dialog" aria-labelledby="modal2Label" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="modal2Label">Modal title</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  Modal 2
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Save changes</button>
                </div>
              </div>
            </div>
          </div>
<div class="container-fluid h-100">
<h1>Modals</h1>
<button type="button" id="btn1" class="btn btn-info btn-lg" data-toggle="modal" data-target="#modal1">Modal 1</button>
<button type="button" id="btn2" class="btn btn-info btn-lg" data-toggle="modal" data-target="#modal2">Modal 2</button>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>     
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/draggable/1.0.0-beta.8/draggable.js" integrity="sha256-IqgasFC+xodVUxVInsmbOaKvevIOjh9iqPUBPd2tyVs=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
    $('.modal-dialog').draggable({
        handle: ".modal-header"
  });
});
</script>
</body>
</html>

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 the World of jQuery Caching and Navigating Through Objects

I'm interested in learning more about jQuery caching and how it can enhance performance. Can you explain how to properly utilize this technique? From what I understand, when using a jQuery selector, you're essentially searching the DOM to create ...

Personalizing the React Bootstrap date picker

I am currently working on customizing the react-bootstrap-daterangepicker to achieve a specific look: My goal is to have distinct background colors for when dates are selected within a range and when the user is hovering over dates to make a selection. I ...

Retrieve information from an Express server using SweetAlert

Hi, I have created a web server using Node.js and Express. When I send a request to ip/test, it returns the text 'test' using res.send('test'). I am trying to fetch this text using sweetalert but I always encounter errors :( Here is t ...

Testing a custom Angular directive that encapsulates the functionality of SlickGrid

Currently, I am working on testing an angular directive that acts as a wrapper for slickgrid. 'use strict'; describe('Unit: Grid Directive', function() { var $scope; var element; beforeEach(module('grid')); beforeEac ...

Using GraphQL in React to access a specific field

Here is the code snippet I am working with: interface MutationProps { username: string; Mutation: any; } export const UseCustomMutation: React.FC<MutationProps> | any = (username: any, Mutation: DocumentNode ) => { const [functi ...

Utilize various CSS styles for individual sections within a multi-page website

Having a web page with multiple subpages each having their own specific CSS can be quite challenging. Sometimes, when all the CSS files are applied globally, they tend to mix with each other causing a headache for developers. One common approach is to decl ...

Removing page scrolling in Bootstrap 5: A step-by-step guide

I would like to ensure that only the card-body block is scrollable. Currently, the page does a bit of scrolling when the card-body block overflows (resulting in 2 scroll bars). The lorem text was added as an example of an overflow. The desired outcome is d ...

Tips for setting a default value in an input type file using JavaScript

While trying to upload a file from my local system to the server, I encountered an issue where the local path was not being set in the input type file field. As a result, I am unable to successfully upload the file. I would greatly appreciate any assistan ...

Exploring the `zoom` CSS attribute and adjusting font sizes on Safari

While my website is somewhat responsive on desktop, the display on iPad or tablet-sized devices leaves much to be desired. Despite having an acceptable layout, everything appears too large, making navigation difficult. It's worth noting that my websit ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...

When the React-bootstrap Popover arrow is oriented vertically, the arrow colors appear to be inverted compared to when it

Utilizing a react-bootstrap Popover component, I have implemented custom styling for the arrow with a gray color and 50% opacity. The CSS code that enables this customization is as shown below: .popover .popover-arrow::before, .popover .popover-arrow::afte ...

What is causing the beforeUpdate hook in Sequelize to fail?

I have a user model with 2 hooks that I am working on. User.beforeCreate(setSaltAndPass) User.beforeUpdate(setSaltAndPass) The first hook works perfectly fine, but the beforeUpdate hook is not triggering as expected. As per the documentation, there should ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

The disconnection event in Node.js socket.io is not being triggered

I've been working on an app using socket io, but I'm having trouble with my disconnect trigger event. I followed the documentation to the letter, but it's still not functioning properly. Strangely enough, it was working just fine a few days ...

Is there a bug in Bootstrap4? The reboot.css seems to be taking precedence over the core Bootstrap, causing

Here is a snippet I found in the Bootstrap Documentation. I have excluded the JavaScript as it is not necessary for my project. Coming from using Bootstrap 3, I am unfamiliar with version 4. However, I noticed that the button text appears black instead of ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

Unlocking bundles of worth through javascript coding

Is there a way to retrieve a set of values using javascript? Upon page load, I am looking to display an alert showing the value '0-1' for any checked checkboxes. View example here var checkBoxes = document.getElementsByName('mailId[]&apos ...

The reactivity of Vuex and Vue does not work as expected when a dictionary is used as a

What is the best approach to make a dictionary reactive as one of my store variables? Unlike an array, dictionaries are not reactive by default. Here's a minimal example I've created: Check out this example on CodeSandbox ...

Create a custom jQuery plugin that enables users to toggle checkboxes with the click of a button

Having trouble with my jQuery button code that is supposed to toggle associated checkboxes but ends up freezing the browser. I am in need of the following functionalities: 1) Clicking on "select all" should select all checkboxes. 2) Clicking on "select all ...

PlaneGeometry at x=0 y=0 z=0 for three.js on a flat surface

Hi there! I have a code snippet that currently renders an image vertically, and I'm looking to modify it so that the PlaneGeometry is drawn horizontally instead. Rather than rotating it with mesh.rotation.x=THREE.Math.degToRad(-90);, I'd like it ...