12

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. ???????

3
  • You can create "modal" using pure JS in many ways - generating HTML elements on demand and injecting them to DOM, manipulating classes on already existing DOM nodes etc. Here is just one, first code example i found after searching for "modal pure javascript" in google: codepen.io/bsngr/pen/yJWJWw Commented Oct 5, 2017 at 4:15
  • 1
    This is not What I am asking about. Commented Oct 5, 2017 at 4:21
  • You're asking for working code that fits your needs then? StackOverflow is to solve problems, not making work for someone else. Commented Oct 5, 2017 at 4:30

8 Answers 8

24

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

Sign up to request clarification or add additional context in comments.

4 Comments

really appreciate your answer, @Nebojsha. Only problem is that the page remains inactive after the modals are closed (the user has to click once to make it active again). Any clue on how to do that inside the function?
I had a conflict between bootstrap modal and jquery modal , and now with this function,i can close any modal
@Muriel My first wild guess is that backdrop is not closed correctly. Please inspect if class name is still 'modal-backdrop' in your version. Or maybe you have multiple backdrops so some of them remain open. In that case you should iterate through all modalBackdrops and close them.
Thanks for this solution! None of the bootstrap methods were working for my use case and it was driving me nuts. Plain ol' JS is the way to go!
8

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();

1 Comment

I extra logged in to say how nifty this is!
6

Follow pure javascript code works fine for my bootstrap5.

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

Comments

2

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");

Comments

1

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.

Comments

0

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();

Comments

0
//Get modal
const bs_modal = document.getElementById(modalId);

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

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

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

Comments

-3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.