12

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:

screencap

alex
  • 6,818
  • 9
  • 52
  • 103
jonathanGB
  • 1,500
  • 2
  • 16
  • 28
  • possible duplicate of [How to prevent a click on a '#' link from jumping to top of page in jQuery](http://stackoverflow.com/questions/3252730/how-to-prevent-a-click-on-a-link-from-jumping-to-top-of-page-in-jquery) – JJJ Jan 30 '15 at 10:59
  • True, but this has a different answer? – jonathanGB Jan 30 '15 at 17:13
  • Both are correct. (Although removing the href attribute has side effects like a different cursor on mouseover.) – JJJ Jan 30 '15 at 17:15
  • Couldn't notice, because I had already changed the cursor in css! – jonathanGB Jan 30 '15 at 17:29

2 Answers2

9

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?

Community
  • 1
  • 1
EdwardM
  • 1,116
  • 11
  • 20
5

Try to change with the code below. It prevents scroll to top when <li> clicked.

<li><a href="javascript:void(0);"> xyz </a></li>
zapoo
  • 1,548
  • 3
  • 17
  • 32