How to programmatically close a Bootstrap modal without using jQuery in JavaScript

Is there a way to make it so that I can close a Bootstrap modal with just one click instead of having to double click? Thanks!

This is the code I'm currently using to close the Bootstrap modal using JavaScript:

// To Close Modal
        document.getElementById('ItemModel').classList.remove('show');
        document.getElementById('ItemModel').style.display = 'none';
        document.getElementsByClassName('modal-backdrop')[0].remove();
        document.body.classList.remove('modal-open');
        document.body.style.padding = '0';

Answer №1

It is widely acknowledged that using workarounds is often necessary. These workarounds can make tasks easier to accomplish, such as the workaround for showing/hiding Bootstrap 4 modals.

For those looking to achieve this without jQuery (but in TypeScript), the following logic can be used:

showModal(){
    let modal = document.getElementById('downloadModal') as HTMLElement;
    let modalDismiss = modal.querySelector('[data-dismiss]') as HTMLButtonElement;
    let backdrop = document.createElement('div') as HTMLElement;

    modal.setAttribute('aria-modal', 'true');
    modal.style.paddingRight = '16px';
    modal.style.display = 'block';
    modal.removeAttribute('aria-hidden');

    document.body.style.paddingRight = '16px';
    document.body.classList.add('modal-open');

    backdrop.classList.add('modal-backdrop', 'fade');
    document.body.appendChild(backdrop);

    backdrop.addEventListener('click', this.hideModal.bind(this));
    modalDismiss.addEventListener('click', this.hideModal.bind(this));

    setTimeout(function(){
        modal.classList.add('show');
        backdrop.classList.add('show');
    }, 200);
}

hideModal(){
    let modal = document.getElementById('downloadModal') as HTMLElement;
    let modalDismiss = modal.querySelector('[data-dismiss]') as HTMLButtonElement;
    let backdrop = document.querySelector('.modal-backdrop');

    modal.classList.remove('show');
    backdrop.removeEventListener('click', this.hideModal.bind(this));
    modalDismiss.removeEventListener('click', this.hideModal.bind(this));

    setTimeout(function(){
        modal.style.display = 'none';
        modal.removeAttribute('aria-modal');
        modal.removeAttribute('style');
        modal.setAttribute('aria-hidden', 'true');
        document.body.removeAttribute('style');
        document.body.classList.remove('modal-open');
        backdrop.remove();
    }, 200);
}

Feel free to translate this into vanilla JavaScript logic without any hindrances.

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

Focus on input using jQuery (fixed focus)

How can I ensure that my input always has value and the focus remains fixed on it until values are typed, preventing the cursor from escaping the input field? While I know the existence of the focus() function, how can I effectively utilize it as an event ...

How can I access an array option that combines both global and target-specific specifications within a grunt plugin?

Currently, I am in the process of creating a grunt plugin that includes options which can consist of arrays of values. These values are specifically file paths (distinct from the files listed in the task's own 'files' property). The setup fo ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

Tips for showing a value in an input text box

Imagine you have a select tag with multiple options. You want to display a specific value in the input field below when a user selects one of the options. <select name="cars" id="cars"> <option value="volvo">Volvo-100</option> < ...

Issue with React component not displaying in the browser.Here are some

I am currently following a React tutorial on and I'm facing an issue where the Counter component is not displaying on the page. The generated HTML looks like this: <html> <head> <script src="/bundle.js" ></script> </he ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

The Google map shifts beyond the perceived limits of the world

Is anyone else encountering an issue with Google Maps where you can now pan beyond the poles? It used to stop at the poles before, correct? The website I'm currently working on runs a location-based query on our server every time a user pans or zooms ...

Unable to suppress error in AngularJS $http.get() call when using catch() method

Below is a simplified version of the code I'm working with, running in CodePen for example: var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { $http.get("https://codepen.io/anon/pen/L ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

Ways to avoid automatic error correction when running npm lint?

Utilizing the Vue CLI, I developed a Vue3 app with a Prettier/Eslint configuration. Upon making changes to the main.ts file as shown below: import { createApp } from "vue"; import App from "./App.vue"; import router from "./router& ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

Encountering an issue with Firebase authentication in Next.js: the window object is not defined

Here is some code snippets: import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { getAuth } from "firebase/auth"; const firebaseConfig = { //credentials// }; export const ...

Combining hover and mousedown event listeners in jQuery: Tips and tricks

htmlCODE: <div class="original_circle" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 0"> <div class="another_circle" style="position:absolute; border-radius: 50%; background-color: coral; width: 40px; h ...

Identify the key name in an array of objects and combine the corresponding values

Here is an example of my array structure: array = [{ "name": "obj0_property0", "url": "picture1" }, { "name": "obj1_property0", "url": "picture1" }, { "name": "obj0_property1", "url": "picture2" }] I am looking to transform this array using J ...

How can I save files to the ~/Documents directory using Node.js on my Mac computer?

Trying to work with the user's Documents folder in Node.js on macOS: var logger = fs.createWriteStream('~/Documents/somefolderwhichexists/'+title+'.txt'); Encountering an error without clear cause. Error message received: Unca ...

Explain the usage of bootstrap col-md-** without resorting to inline styling

Consider the example below <html> <head> </head> <body> <div class="col-xs-12 col-sm-12 offset-md-4 col-md-4 offset-lg-4 col-lg-4"></div> <div class="col-xs-12 col-sm-12 offset-md-4 col-md-4 offset-lg-4 col-lg- ...

Toggle class to a div upon clicking menu item

Seeking assistance with jQuery to develop a video player featuring a sub menu for displaying various content options upon selection. Here is a snapshot of the frontend design: view image Upon clicking on 'video' or 'audio', a distinct ...

Is AngularJS known for its ability to bind variables across different components effortlessly

In the beginning of my Angular controller, I use Promises to download JSON data and then store it in variables: app.controller('mainController', ['$scope', '$http', '$q', function($scope, $http, $q) { var req1 = $ ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

Enable next-i18next to handle internationalization, export all pages with next export, and ensure that 404 error pages are displayed on non-generated pages

After carefully following the guidelines provided by i18next/next-i18next for setting up i18n and then referring to the steps outlined in this blog post on locize on how to export static sites using next export, I have managed to successfully generate loca ...