Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Bootstrap Dropdown with JS

Tags:

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');
});
like image 907
jacksondc Avatar asked Jan 10 '14 03:01

jacksondc


People also ask

How do you toggle a dropdown in Bootstrap?

Dropdowns are toggleable, contextual overlays for displaying lists of links and more. They're made interactive with the included Bootstrap dropdown JavaScript plugin. They're toggled by clicking, not by hovering; this is an intentional design decision.

How do you open Bootstrap dropdown menu on hover rather than click?

Answer: Use the jQuery hover() method By default, to open or display the dropdown menu in Bootstrap you have to click on the trigger element. However, if you want to show the dropdown on mouseover instead of click you can do it with little customization using the CSS and jQuery.

How do I create a dropdown in Bootstrap?

To open the dropdown menu, use a button or a link with a class of . dropdown-toggle and the data-toggle="dropdown" attribute. The . caret class creates a caret arrow icon (), which indicates that the button is a dropdown.


1 Answers

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/

like image 167
Phil Avatar answered Sep 24 '22 14:09

Phil