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');
});
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With