I have two Bootstrap dropdown menus (split buttons). When the dropdown is active, the user can press on numbers going from 1 to 5, but when they press any of these, the user is redirected to the top of the page.
I understand that it's normal behavior (considering that they are clicking a "link"), but I want to prevent this effect because it affects the mobile experience. I tried to use return false
in my jQuery code, but by doing so, when the dropdown is active, no element can be selected in the dropdown. Is there an alternative?
HTML:
<div id="btn1">
<div class="btn-group dropup">
<button type="button" class="btn btn-primary">Add 1 vector</button>
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu" id="ajouter">
<li><a href="#">1</a> </li>
<li><a href="#">2</a> </li>
<li><a href="#">3</a> </li>
<li><a href="#">4</a> </li>
<li><a href="#">5</a> </li>
</ul>
</div>
</div>
jQuery:
$('#ajouter a').on('click', function() {
nombre_ajout = parseInt($(this).html());
if (nombre_ajout > 1)
$('#btn1 button').eq(0).html('Add ' + nombre_ajout +' vectors');
else if (nombre_ajout == 1)
$('#btn1 button').eq(0).html('Add ' + nombre_ajout +' vector');
});
Image:
As all Twitter Bootstrap users know, the dropdown menu closes on click (even clicking inside it). To avoid this, I can easily attach a click event handler on the dropdown menu and simply add the famous event. stopPropagation() .
For Bootstrap 4, look for the clickEvent , and when found in the hide event, prevent the default close behavior. This dropdown will only close when the button is clicked. In some cases, you may want the Dropdown to close when the button or menu is clicked. In this case you can examine the clickEvent target.
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.
You can try removing the "href" attribute all together on the anchors?
See this post on this: Valid to use <a> (anchor tag) without href attribute?
Try to change with the code below. It prevents scroll to top when <li>
clicked.
<li><a href="javascript:void(0);"> xyz </a></li>
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