How to toggle modal windows in bootstrap?

I have two buttons that triggers different modal windows, but I can't get to make when I click in one of the buttons (and trigger its corresponding modal window), if the other modal windows is opened, close the other. Simple as: if I open a modal and the other modal is opened, close the currently opened one and open the new. I'm using bootstrap modals.

This triggers one modal window

<button class="magicon" data-toggle="modal" 
         data-target="#modalsearch" data-backdrop="false"></button>
<div id="modalsearch" class="modal fade" tabindex="-1" 
         role="dialog" aria-labelledby="labelmodalsearch" aria-hidden="true"></div>

And this triggers the other

<button class="navicon" data-toggle="modal" 
         data-target="#modalmenu" data-backdrop="false"></button>
<div id="modalmenu" class="modal fade" tabindex="-1" 
         role="dialog" aria-labelledby="labelmodalmenu" aria-hidden="true"></div>

thanks for your help!


this is the working site, check how the magnifier glass icon and the hamburger icon behaves when opening their corresponding modal windows.

http://www.byalexander.com.au/rotary-youth-art-project-cc-x-ccp-2017-2/

Upvotes: 0

Views: 216

Answers (1)

Levon Grigoryan
Levon Grigoryan

Reputation: 373

This should work:

$('.modal').on('show.bs.modal', function(e) {

    $('.modal').not(this).modal('hide');

 });
 $('.modal').on('hide.bs.modal', function(e) {

   var $btnRelated = $(e.relatedTarget);
    $btnRelated.hasClass('open') && $btnRelated.removeClass('open');

 });

Code was updated, so the button states are also considered, as per your site.

Upvotes: 1

Related Questions