简体   繁体   中英

Close Bootstrap Modal (using Javascript Not Jquery) when execute a function

i wanna close bootstrap modal when execute a function i did it but when open modal again i have to double click to open it i wanna open it again with one click not double, Thanks

my code to close bootstrap modal (js)

// 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';

I believe we all know it's most likely a workaround. Sometimes this will get the job done more easy. Hence a workaround to show/hide Bootstrap 4 modals.

Without jQuery (but in TypeScript) you can use the following logic:

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

I hope this doesn't stop you from converting it to vanilla JavaSript logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM