Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Bootstrap Modal using Pure JavaScript On Click

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

like image 319
Jone Doe Avatar asked Oct 05 '17 04:10

Jone Doe


3 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

like image 103
Nebojsha Avatar answered Nov 03 '22 22:11

Nebojsha


Follow pure javascript code works fine for my bootstrap5.

let myModalEl = document.getElementById('modal1')
let modal = bootstrap.Modal.getInstance(myModalEl)
modal.hide()
like image 30
RuiG Avatar answered Nov 04 '22 00:11

RuiG


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

like image 28
Emmanuel Ndukwe Avatar answered Nov 03 '22 23:11

Emmanuel Ndukwe