0

I have a Bootstrap dropdown button with the following markup:

<div class="btn-group dropup">
    <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">Test<span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a href="#">Link 1</a>
            <a href="#">Link 2</a>
            <a href="#">Link 3</a>
        </li>
    </ul>
</div>

When you click on a.dropdown-toggle, Bootstrap's javascript toggles the ul.dropdown-menu's visibility by adding the class open to the div.btn-group. All this is well and good.

The problem I'm experiencing occurs when I add my own javascript function to the a.dropdown-toggle's click event. Something like this:

$('a.dropdown-toggle').click(function (e) {
    e.preventDefault();
    $('a.dropdown-toggle').html('Testing...');
});

When I do this something weird happens. When you click the button, it expands the menu as desired EXCEPT when you click directly on the .caret in the button. When you click directly on the .caret, it only executes my click event.

How can I resolve this and have clicks directly on the .caret toggle the menu like clicking anywhere else on the button does.

http://jsfiddle.net/UZkQL/

2
  • What about ' e.stopPropagation();' at the end of script ? Commented Mar 25, 2014 at 21:17
  • This did nothing as could be seen if you added it to the jsfiddle. Commented Mar 26, 2014 at 14:31

1 Answer 1

1

In your fiddle you have:

$('a.dropdown-toggle').html('Testing...<span class="caret"></span>');

The issue is that you recreate the span element with the carat, which seems to make it not have a click handler bound to it. A quick and dirty fix would be:

$('a.dropdown-toggle').click(function (e) {
    e.preventDefault();
    if ($('a.dropdown-toggle').text().indexOf('ing...') == -1) {
        $('a.dropdown-toggle').find('span').before('ing...');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Weird. I'm not sure how I didn't realize this was happening. In my solution, I'm going to keep the caret span and have the button text in a separate span, neither of which will ever be removed. I'll conditionally hide the caret span and change the text span contents as my logic dictates. Thanks for pointing me in the right direction!

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.