简体   繁体   中英

Trigger jQuery on Bootstrap dropdown toggle

I made a bootply that won't generate a link, so here's my settings that I threw in there.

I want to have jQuery add a class to another div when this dropdown is triggered, and remove the class when the dropdown is hidden.

CSS:

.halfOpacity
  {
    opacity: .5;
  }
#switchMenu
  {
    top: 100px;
  }
#siteData
  {
    color: #FFF;
    background-color: #000;
  }

Javascript:

$('#switchDropdown').on('show.bs.dropdown', function(){
  $('#siteData').addClass('halfOpacity');
});
$('#switchDropdown').on('hide.bs.dropdown', function(){
  $('#siteData').removeClass('halfOpacity');
});

HTML:

<a href="#" class="navbar-brand dropdown-toggle mobile-footer-brand" data-toggle="dropdown" id='switchDropdown'>Test Link</a>

<ul class='dropdown-menu' id='switchMenu'>
  <li>HORRAY!!!!</li>
</ul>

<div id='siteData'>Some Stuff<br>Moar stuff<br>Even moar stuffs</div>

Right now the jQuery never gets called based off of the actions that Bootstrap says happen.

Answered my own question with reading documentation more clearly.

Events

All dropdown events are fired at the .dropdown-menu 's parent element.

Bootstrap Documentation Here

The following changes fixed it for me:

Javascript:

$('#wrap').on('show.bs.dropdown', function(){
  $('#siteData').addClass('halfOpacity');
});
$('#wrap').on('hide.bs.dropdown', function(){
  $('#siteData').removeClass('halfOpacity');
});

HTML:

<div id='wrap'>
<a href="#" class="navbar-brand dropdown-toggle mobile-footer-brand" data-toggle="dropdown" id='switchDropdown'>Test Link</a>

<ul class='dropdown-menu' id='switchMenu'>
  <li>HORRAY!!!!</li>
</ul>
</div>
<div id='siteData'>Some Stuff<br>Moar stuff<br>Even moar stuffs</div>

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