Home > Blockchain >  How to open a specific Bootstrap tab located on a modal by URL?
How to open a specific Bootstrap tab located on a modal by URL?

Time:08-12

I would like to open a specific tab in a modal by URL. To open the modal I added following JavaScript to the end of the website. By entering website.com/#modal-6 it opens the website with modal-6 activated.

document.addEventListener("DOMContentLoaded", function() {
    if (window.location.href.indexOf("#modal-6") > -1) {
        var myModal = new bootstrap.Modal(document.getElementById('modal-6'));
        myModal.show();
    }
});

This modal contains a several tabs. How can I achieve that the tab with id=tab-13 is shown, when loading the website through website.com/#modal-6?

The HTML code is as follows:

<ul id="tabContainer-11"  role="tablist">
    <li  role="presentation">
        <button id="tab-12"  data-bs-target="#tab-content-12" data-bs-toggle="tab" role="tab" aria-controls="tab-content-12" aria-selected="false"> Login </button>
    </li>
    <li  role="presentation">
        <button id="tab-13"  data-bs-target="#tab-content-13" data-bs-toggle="tab" role="tab" aria-controls="tab-content-13" aria-selected="true"> ...or subscribe now! </button>
    </li>
</ul>

CodePudding user response:

You'd leverage the modal event shown.bs.modal to call the function to show your tab, using tab.show(). See docs for modal events and tab methods.

CodePudding user response:

Awesome! Thanks for pointing me there!

So the code is:

//show modal with id=modal-6, if url contains "#modal-6"    
document.addEventListener("DOMContentLoaded", function() {
            if (window.location.href.indexOf("#modal-6") > -1) {
                    var myModal = new bootstrap.Modal(document.getElementById('modal-6'));
                    //var myTab = new bootstrap.Tab(document.getElementById('tab-13'));
                    myModal.show();
            }
    });
//open tab with id=tab-13, when modal is shown
    var myModalEl = document.getElementById('modal-6')
    myModalEl.addEventListener('shown.bs.modal', function (event) {
      // do something...
      var myTab = document.querySelector('#tab-13');
      var tab = new bootstrap.Tab(myTab);
    
      tab.show();
    });
  • Related