13

I have an element, dropdown, and some jquery to toggle the dropdown dynamically. However, the toggle doesn't work when called from the event handler. I've already tried everything suggested by related Stackoverflow answers, but nothing works :(

JavaScript:

$(function(){
  //$(".dropdown-toggle").dropdown('toggle'); // this works
  $('#click').click(function(){
    $(".dropdown-toggle").dropdown('toggle'); // this doesn't
  });
});

HTML:

<div class="dropdown clearfix">
   <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>
   <ul id="dropdown" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
      <li><a tabindex="-1" href="#">Action</a></li>
      <li><a tabindex="-1" href="#">Another action</a></li>
      <li><a tabindex="-1" href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a tabindex="-1" href="#">Separated link</a></li>
    </ul>
  </div>
<br>
<div id="click">Click to toggle</div>

And here is the working (not!) sample: http://bootply.com/61988

2 Answers 2

23

Just stop the event from propagating and it should work.

$(function(){
  //$(".dropdown-toggle").dropdown('toggle'); // this works
  $('#click').click(function(e){
      e.stopPropagation();
    $(".dropdown-toggle").dropdown('toggle');// this doesn't
  });
});

Fiddle

Bootply

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

4 Comments

Worked like a charm! Although my real situation was a lot more complicated than that, your answer helped me out.
It saves my time :) I was trying to fix this since last 1+ hour... Thanks by the way
After all the other answers I tried, this one worked! Thank you sir!
This is the best answer, after a lot of time wasted in useless answers ! Thank you so much
0

For the vue user here,. you can use this.

<div class="dropdown clearfix">
   <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>
   <ul id="dropdown" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
      <li><a tabindex="-1" href="#">Action</a></li>
      <li><a tabindex="-1" href="#">Another action</a></li>
      <li><a tabindex="-1" href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a tabindex="-1" href="#">Separated link</a></li>
    </ul>
  </div>
<br>
<div @click.stop="toggleDropdown()">Click to toggle</div>

script

methods: {
   toggleDropdown(){
       $(".dropdown-toggle").dropdown('toggle');
   }
}

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.