What is an alternative method to trigger a Bootstrap modal without using jQuery or bootstrap.js JavaScript code?

I am currently developing a survey application that is designed to be extremely lightweight. This application is specifically tailored for use in third world countries where internet connection is very limited.

After conducting some research, we discovered that the loading time of the application is directly related to user engagement, which is incredibly important to us.

As of now, I am utilizing two libraries - VueJS and a custom bootstrap build. I want to implement a modal feature, but doing so would require adding Bootstrap Javascript and jQuery, ultimately doubling the loading time of the application.

Is there a way for me to include a modal in my application without having to incorporate these two libraries?

Answer №1

The CSS only modal link shared by @uday is clever, but it may not be ideal if you are using #tags for other purposes such as Routing & param passing.

Here's an alternative approach that requires minimal JS to achieve a similar result. I've kept the code snippet concise for easy understanding.

var modal = document.querySelector(".modal");
var container = modal.querySelector(".container");

document.querySelector("button").addEventListener("click", function (e) {
  modal.classList.remove("hidden")
});

document.querySelector(".modal").addEventListener("click", function (e) {
  if (e.target !== modal && e.target !== container) return;     
  modal.classList.add("hidden");
});
.modal {
  background-color: rgba(0,0,0,0.4); /* Transparent dimmed overlay */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: table;
}

.modal.hidden {
  display: none;
}

.modal .container {
 display: table-cell;
 text-align: center;
 vertical-align: middle;
 width: 200px;
}

.modal .body {
  box-shadow: 5px 10px #888888;
  display: inline-block;
  background-color: white;
  border:
   1px solid black; 
  padding: 10px;
}
<button>Show Modal</button>

<div class="modal hidden">
  <div class="container">
    <div class="body">
      <p>Click outside this box to close the modal.<p>
      <p>You could of course add a close button etc</p>
      <p>But this is left for the OP todo</p> 
    </div>
  </div>
</div>

Answer №2

To implement a Bootstrap modal in your HTML without needing any additional CSS styles, you can follow these steps:

var locModal = document.getElementById('locModal');
var btnclose = document.getElementById('w-change-close');
var btnShow= document.getElementById('w-change-location');

// Show the modal
btnShow.addEventListener('click', (e) => {
    locModal.style.display = "block";
    locModal.style.paddingRight = "17px";
    locModal.className="modal fade show"; 
});

// Hide the modal
btnclose.addEventListener('click', (e) => {
    locModal.style.display = "none";
    locModal.className="modal fade";
});

Your HTML structure should include the following code for the button trigger and modal:

<!-- Button trigger modal -->
<button id="w-change-location" type="button" class="btn btn-primary mt-3" data-toggle="modal" data-target="#locModal">
    Change Location
</button>

<!-- Modal -->
<div class="modal fade" id="locModal" tabindex="-1" role="dialog" aria-labelledby="locModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="locModalLabel">Choose Location</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form action="" id="w-form">
                    <div class="form-group">
                        <label for="city"> City</label>
                        <input type="text" class="form-control" id="city">
                    </div>
                    <div class="form-group">
                        <label for="state"> State </label>
                        <input type="text" class="form-control" id="state">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button id="w-change-close" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button id="w-change-btn" type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Answer №3

We have developed custom code to create our own modal.

let modal = document.getElementById('our-modal');
let modalContentElm = modal.querySelector('.modal-content');
let allModalButtons = modal.querySelectorAll('.modal-footer > .btn');
let outerClick = true;

let openStyle = () => { //DISPLAY MODAL
    modal.style.backgroundColor = 'rgba(0,0,0,0.5)';
    modal.style.display = 'block';
    setTimeout(() => { modal.style.opacity = 1; }); //FOR TRANSITION 
};
let closeStyle = () => { //HIDE MODAL
    modal.style.display = 'none';
    modal.style.opacity = 0;
};

//PREVENT CLOSING MODAL WHEN CLICKING INSIDE THE MODAL
modalContentElm.onclick = () => {
    outerClick = false;
};

//CLOSE MODAL WHEN CLICK OUTSIDE THE MODAL
modal.onclick = () => {
    if(outerClick){ closeStyle(); }
    outerClick = true;
};


for(let btn of allModalButtons){
    btn.onclick = () => {

        closeStyle();

        if(btn.getAttribute('id') === 'success-btn'){
            //MAKE SURE TO SET 'success-btn' AS ID FOR THE CONFIRM BUTTON
            console.log('Clicked Yes');
        }
        else{
            console.log('Clicked Cancel');
        }
        //..... add more conditions for other modal buttons

    };
}

To open the modal, use the following:

openStyle();

To manually close the modal, use the following:

closeStyle();

Although a bit cumbersome, this method is effective. A more universal class could streamline the process.

Answer №4

If you're working with bootstrap 5, it's simple to display or conceal a modal using JavaScript:

Check out the documentation here

const customModal = new bootstrap.Modal(document.getElementById('customModal')); // creating modal object
customModal.show(); // show modal
customModal.hide(); // hide modal

Answer №5

If you are looking to implement Bootstrap Modal CSS, here is a simple Javascript snippet that demonstrates how to toggle the modal:

const dialog = document.querySelector(".modal-container");

document.querySelector(".btn-close").addEventListener("click", () => {
  dialog.classList.add("d-none");
});

document.querySelector(".btn-show").addEventListener("click", () => {
  dialog.classList.remove("d-none");
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac8c5c5ded9ded8cbdaea9f84988499">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<button class="btn-show btn btn-primary">Show Dialog</button>

<div class="modal-container d-none">
  <div class="modal-backdrop show"></div>
  <div class="modal show d-block" tabindex="-1">
      <div class="modal-dialog">
          <div class="modal-content">
              <div class="modal-header">
                  <h5 class="modal-title">
                      Dialog Title
                  </h5>
                  <button class="btn-close"></button>
              </div>
              <div class="modal-body text-center">
                  Dialog Content
              </div>
          </div>
      </div>
  </div>
</div>

  • .modal-backdrop creates the black backdrop behind the dialog.
  • The div with .modal needs to have d-block for it to display correctly as the default CSS property is set to display: none.
  • Make sure to include .show classes for both the .modal-backdrop and .modal.

Answer №6

To activate the modal using a button, simply include the bootstrap options in the button tag:

data-bs-toggle="modal" data-bs-target="#modalTarget"
. You can also add an onclick function like this: onclick="openModal();"

function openModal(){
   console.log("Modal is now open");
}

Answer №7

Experimenting with Laravel 9 and Bootstrap 5, I successfully implemented a modal without using jQuery.

Here is the process I followed to delete data utilizing the modal named deleteModal:

  • 1- Placed wire:ignore.self in the Div modal to ensure it opens and remains open.

  • 2- Added the following line at the end of the function for deleting data:

    $this->dispatchBrowserEvent('closeModal');

    This triggers the event named "closeModal".

  • 3- Included @stack('script') to listen for scripts.

  • 4- Inserted the script below:

@push('script')
    <script>
        window.addEventListener('closeModal', event => {
            document.querySelector('#deleteModal').style.display = "none";
            document.querySelector('.modal-backdrop').remove();
        })
    </script>
@endpush

This script handles the closing of the modal.

The dark background behind the Modal is created by the div with the class "modal-backdrop" placed at the end of the HTML page.

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

Reactjs: Issue with functionality of input field

My project includes an input field for adding email tags, which I initially created using React JS. The functionality worked seamlessly in the JavaScript file, but when I converted it to TypeScript, I encountered a issue where I couldn't type or paste ...

Utilizing React and Material-UI to Enhance Badge Functionality

I am exploring ways to display a badge icon when a component has attached notes. I have experimented with three different methods and interestingly, the results are consistent across all of them. Which approach do you think is the most efficient for achiev ...

Is it possible for bootstrap to be integrated with specific CSS styles?

I want to utilize bootstrap to create some columns using predefined classes like .col-sm-, and include additional widths for smaller phones. Despite seeing the layout looking fine on Chrome and a few devices, Netbeans throws a "class not found" message for ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

How to Shift Focus to a Component in Vue.js

Within a container, I have a form section enclosed by a component that remains hidden due to the use of v-if. Upon clicking a button, the boolean value is toggled, revealing the previously concealed component. At this point, I aim to shift focus to the ini ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

Concealing the table border with the help of jQuery

I am working with a dynamically created tables in a ASP.NET repeater, where the number of tables can vary depending on the data retrieved from the database. Below is a sample markup along with the CSS and jQuery code. Please note that the tables are dynami ...

``There seems to be an issue with implementing the SlideDown feature in JavaScript

I am having an issue with a code where the expected behavior is to slide down a div when a person hovers over text, but it's not working. Can someone please review and identify the cause of this problem? <script type="text/javascript" src="/js/jqu ...

Tips for creating a side by side layout in Bootstrap modal content

I recently ventured into using Bootstrap and decided to create a simple modal based on the Bootstrap 4 documentation. You can check out the Bootstrap 4 modal for reference. The modal I created consists of two parts - Part 1 and Part 2, with a <hr> t ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

Tips for embedding the <img> element inside the <a> element

I'm attempting to place an image within a hyperlink tag. Current code: <div class="Sample"> <a href="http://www.Sample.com"> <img src="http://www.Sample.com/Sloth.jpg"> </a> </div> I wish to add <img class= ...

Minimizing conditional statements in my JavaScript code

I've just completed the development of a slider and am currently working on optimizing some repetitive if/else statements in the code. The purpose of these conditions is to determine whether the slider has reached the last slide, in which case the nex ...

Execute a function on elements that are added dynamically

I'm in the early stages of learning javascript and jquery, so this issue might be very basic. Please bear with me. Currently, I am dynamically adding new link (a) elements to a division with the id "whatever" using the following code: $("#whatever") ...

Unable to execute two functions consecutively

After running the code, I encountered the error message Uncaught TypeError: object is not a function and only the status function is working properly. Can anyone help me identify the issue? $(document).ready(function() { steam('status', 60 ...

Using a Sequelize query in a subsequent query for reusability

I am facing an issue with reusing a query from another function within a WITH clause of a separate query. I experimented with the following code snippet to tackle this challenge. Here is a snippet to provide a general overview. const reuseQuery = async (I ...

Trouble with Firebase/Firestore documentation queries in JavaScript

Having trouble using the new Firestore system. I'm trying to retrieve a Collection of all users and go through it, but I can't seem to make it work. db.collection("users").get().then(function(querySnapshot){ console.log(querySnapshot.dat ...

it is impossible to create a hyperlink for a URL

I am trying to add a hyperlink to a URL on my website, but for some reason the link is not working when I click on it or copy and paste it into the web address bar. The URL only seems to work when clicked directly from the original website. Additionally, w ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

Transferring MySQL data from PHP to Javascript using JSON format

I am attempting to utilize a code snippet that fetches data from a mySQL database, assigns that data to a variable, aggregates all the resulting values into a PHP array, and then converts it to JSON format. Subsequently, I transfer the JSON data to JavaScr ...

Implementing the Tab key functionality without redirecting to the address bar

I recently integrated a Tab control into my project, but I'm encountering an issue where pressing the Tab key causes the address bar to jump when I try to press another key. This only happens after the Tab key functions correctly in the scene. How can ...