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. ???????
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
Follow pure javascript code works fine for my bootstrap5.
let myModalEl = document.getElementById('modal1')
let modal = bootstrap.Modal.getInstance(myModalEl)
modal.hide()
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With