1

I am trying to build a CMS using Symfony in which I am trying to use Vanilla JS instead of jQuery. I am displaying a modal with some info on page load.

If I do $("#companies").modal(); the bootstrap modal is displayed correctly.

Until now I thought let companies = $("#companies"); and let companies = document.getElementById('companies'); were equivalent. But when I tried to call the modal function on the element returned by Javascript getElementById, it gave me error modal() is not a function.

How can I call the Bootstrap modal function using an element returned by getElementById function? Thanks.

2 Answers 2

1

You cannot use bootstrap without jquery. All js components have jquery dependency. To use bootstrap without jquery, you need bootstrap clone like bootstrap.native

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

2 Comments

I have jQuery included in my project but I just want to minimise its usage in my custom code. I want to display this modal using JavaScript.
as i said you cannot bootstrap components without jquery. check getbootstrap.com/docs/4.2/getting-started/introduction/#js
1

Here is a way you could manually do it the Vanilla 😋😋 way

function toggleModal() {
    const yourModal = document.getElementById('companies');
    document.querySelector('body').classList.toggle('modal-open');
    if (yourModal.style.display == 'block') {
        yourModal.style.display = 'none';
        yourModal.classList.remove('in'); 
        document.querySelector('.modal-backdrop').remove(); //remove shadow
        document.querySelectorAll('#companies [data-dismiss="modal"]').forEach((elem, index) => elem.removeEventListener('click', toggleModal)); //remove listeners

    } else {
        yourModal.style.display = 'block';
        yourModal.classList.add('in');
        //backdrop effect
        const shadow = document.createElement('div');
        shadow.classList.add('modal-backdrop');
        shadow.classList.add('fade');
        shadow.classList.add('in');
        document.querySelector('.container').appendChild(shadow);
        //add event listeners for dismissing dialog
        document.querySelectorAll('#companies [data-dismiss="modal"]').forEach((elem, index) => elem.addEventListener('click', toggleModal)
        );
    }
}

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.