Hide Bootstrap Modal using Pure JavaScript On Click

Viewed 23222

I was working on Bootstrap Pop Up Modals.

I have 2 Buttons named Button1 & Button2.

&

I have 2 Modals named Modal1 & Modal2.

Note : Button2 is inside the Modal1 & Button1 is on the Web Page.

If I click Button1 , Modal1 should be Open & If I click Button2 that is inside the Modal, then Modal1 should be hide automatically and Modal2 should be shown.

I am doing it using jQuery Yet & It's working Fine.

<script>
$('#button1').click(function()
{
    $('#modal1').modal('hide');
    $('#modal2').modal('show');
});
</script>

Question:

How I can do it using Pure JavaScript. ???????

7 Answers

Here is workaround I wrote in order to close modal in native Java Script, using DOM manipulation. Bootstrap 4 is used.

function closeAllModals() {

    // get modals
    const modals = document.getElementsByClassName('modal');

    // on every modal change state like in hidden modal
    for(let i=0; i<modals.length; i++) {
      modals[i].classList.remove('show');
      modals[i].setAttribute('aria-hidden', 'true');
      modals[i].setAttribute('style', 'display: none');
    }

     // get modal backdrops
     const modalsBackdrops = document.getElementsByClassName('modal-backdrop');

     // remove every modal backdrop
     for(let i=0; i<modalsBackdrops.length; i++) {
       document.body.removeChild(modalsBackdrops[i]);
     }
  }

So this function closes all modals found on page. You can modify it to close one certain modal based on id. This way:

function closeOneModal(modalId) {

    // get modal
    const modal = document.getElementById(modalId);

    // change state like in hidden modal
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden', 'true');
    modal.setAttribute('style', 'display: none');

     // get modal backdrop
     const modalBackdrops = document.getElementsByClassName('modal-backdrop');

     // remove opened modal backdrop
      document.body.removeChild(modalBackdrops[0]);
  }

So, no clue of jQuery at all

You could just assign an id to a button that would normally dismiss/open the modal, the simulate a click on the button to programmatically dismiss/open a modal.

e.g - $('#modal1').modal('hide'); $('#modal2').modal('show'); would become document.getElementById('modalX').click();

Here is a working solution:

https://codepen.io/hamzeen/pen/MErYgp.

You can achieve it without writing any Javascript in your app YET, I couldn't find a way to do it with plain javascript. The data-target property on the anchor tag handles the toggle, check the code below:

<a href="#" class="btn btn-lg btn-danger" data-toggle="modal" data-
target="#modal1">Open Modal 1</a>

I found the following from Bootstrap's Javascript Library, probably this helps you!

/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript 
requires jQuery");

Follow pure javascript code works fine for my bootstrap5.

let myModalEl = document.getElementById('modal1')
let modal = bootstrap.Modal.getInstance(myModalEl)
modal.hide()

You can create a 'modal' element using javascript. The advantage is that you can reuse it. I have created a sample bootstrap modal using javascript. You can modify it to add more features.

var Interface = {};
Interface.component = function ( dom ) {
    this.dom = dom;
};
Interface.component.prototype = {
    setId: function ( id ) {
        this.dom.id = id;
        return this;
    }
    // you can add more common functions here
};

Interface.BootstrapModal = function ( id, modalHeading, modalBodyContents, successButtonText, failureButtonText ) {

    var scope = this;
    var dom = document.createElement( 'div' );
    dom.className = 'modal fade';
    dom.id = id;
    dom.role = "dialog";

    var modalDialog = document.createElement( 'div' );
    modalDialog.className = 'modal-dialog';

    var modalContent = document.createElement( 'div' );
    modalContent.className = 'modal-content';

    var modalHeader = document.createElement( 'div' );
    modalHeader.className = 'modal-header';

    var modalHeaderXButton = document.createElement( 'button' );
    modalHeaderXButton.className = 'close';
    modalHeaderXButton.setAttribute("data-dismiss", "modal");
    modalHeaderXButton.innerHTML = '&times';

    var modalHeaderHeading = document.createElement( 'h3' );
    modalHeaderHeading.className = 'modal-title';
    modalHeaderHeading.innerHTML = modalHeading;

    modalHeader.appendChild(modalHeaderXButton);
    modalHeader.appendChild(modalHeaderHeading);

    var modalBody = document.createElement( 'div' );
    modalBody.className = 'modal-body';
    modalBody.appendChild(modalBodyContents);

    var modalFooter = document.createElement( 'div' );
    modalFooter.className = 'modal-footer';

    var modalFooterSuccessButton = document.createElement( 'button' );
    modalFooterSuccessButton.className = 'btn btn-success';
    modalFooterSuccessButton.id = "<GIVE THE ID YOU NEED>";
    //modalFooterSuccessButton.setAttribute("data-dismiss", "modal");
    modalFooterSuccessButton.innerHTML = successButtonText;

    var modalFooterFailureButton = document.createElement( 'button' );
    modalFooterFailureButton.className = 'btn btn-danger';
    modalFooterFailureButton.id = "<GIVE THE ID YOU NEED>";
    modalFooterFailureButton.setAttribute("data-dismiss", "modal");
    modalFooterFailureButton.innerHTML = failureButtonText;

    modalFooter.appendChild(modalFooterSuccessButton);
    modalFooter.appendChild(modalFooterFailureButton);

    modalContent.appendChild(modalHeader);
    modalContent.appendChild(modalBody);
    modalContent.appendChild(modalFooter);
    modalDialog.appendChild(modalContent);

    dom.appendChild(modalDialog);

    modalFooterSuccessButton.addEventListener( 'click', function ( event ) {

        // perform your actions

    } );

    this.dom = dom;
    return this;

};

Interface.BootstrapModal.prototype = Object.create( Interface.component.prototype );
Interface.BootstrapModal.prototype.constructor = Interface.BootstrapModal;

Interface.BootstrapModal.prototype.show = function () {

    $('#' + this.dom.id).modal({backdrop: 'static', keyboard : false});

};

Interface.BootstrapModal.prototype.hide = function () {

    $('#' + this.dom.id).modal('hide');

};

Here I have created the modal element as an object. You can use it like,

var modalContent = document.createElement( 'div' );
var m = new Interface.BootstrapModal( 'id', 'modalHeading', modalContent, 'successButtonText', 'cancelButtonText' );
document.getElementById( <SOME ELEMENT> ).appendChild( m.dom );

now m.show() will show the modal and m.hide() will hide the same

This can be used as a general template for bootstrap modals.

Here's how to get modal.hide() (and all other modal methods too!) in pure JS.
You can try it on official docs page, let's take modal documentation as an example here. The catch is, the modal stores a property looking like 'jQuery331042511280243656492' on the modal DOM object. This property has all the modal methods inside! Just open this modal first, then run the code in console.

UPDATE: that jQuery object is only attached on 1st opening of the modal, and is present from then on. That means, that we can not '.show()' our modal via this method, unless we've already opened it at least once.

    // get reference to the modal. It's 'div.modal', in general
    var modal = document.querySelector('#exampleModalLong');
    // get the key under which the modal's methods are stored.
    var jQueryObj = Object.keys(modal).filter((key) => (key.toString().indexOf('jQuery') !== -1) && modal[key].hasOwnProperty('bs.modal'));
    // ... and close the modal!
    modal[jQueryObj]['bs.modal'].hide();

Can you try this....

function showmodel(){
var Modal1 = document.getElementById("Modal1"); 
Modal1.show(); 
}
function hidemodel1()
{
var Modal1 = document.getElementById("Modal1"); 
var Modal2 = document.getElementById("Modal2"); 
Modal1.hide(); 
Modal2.show(); 
}

Call the above method in button onclick.

Related