23

I need to open a Bootstrap dropdown menu via JavaScript. This answer suggests adding and removing the open class, but when I try that, nothing happens. Adding a different class works fine. Is Bootstrap preventing me from doing this?

Working sample on JSFiddle.

HTML

<input type="button" value="Add Classes" />
<div class="dropdown">
    <a data-toggle="dropdown" href="#">Dropdown Trigger</a>
    <div class="dropdown-menu">Dropdown Content</div>
</div>

JS

$('input').click(function () {
    $('.dropdown').addClass('open');
    $('.dropdown').addClass('test-class');
});
1
  • 1
    @Popnoodles, I have added code from jsfiddle to question. Commented Jan 10, 2014 at 3:29

2 Answers 2

42

Your main problem is that you aren't stopping the click event from propagating to the document. Bootstrap sets an event listener on the document that closes dropdowns.

$('input').on('click', function (e) {
    e.stopPropagation();
    $(this).next('.dropdown').find('[data-toggle=dropdown]').dropdown('toggle');
});

jsFiddle - http://jsfiddle.net/8p6Wd/2/

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

1 Comment

@Popnoodles That's true but the OP's code doesn't set any of the internal state or trigger the custom events usually associated with the Dropdown plugin.
2

try this...

<div class="dropdown">
    <input type="button" value="Classes" data-toggle="dropdown"/>
    <a data-toggle="dropdown" href="#">Dropdown Trigger</a>
    <div class="dropdown-menu">Dropdown Content</div>
</div>

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.