Reputation: 81
The dropdown menu which is being used is of bootstrap. The code is as below
<li id="changethis" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">LINK</a>
<ul class="dropdown-menu">
<li id="clickme"><a href="#">Link1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</a>
<li>
Jquery code looks like this
$(document).ready(function () {
$('#clickme').on('click', function () {
$('#changethis').removeClass('dropdown');
$(this).addClass('dropdown open');
});
});
On click of Link1, I wish to change the li class to dropdown open. I am not getting any error in my console, but the dropdown class is not changed.
Upvotes: 1
Views: 6901
Reputation: 29829
As Jack pointed out, you should be able to handle the click on your list item and prevent it from bubbling up with event.stopPropagation()
like this:
$('#clickme').click(function (e) {
e.stopPropagation()
});
Demo in Stack Snippets:
$('#clickme').click(function (e) {
e.stopPropagation()
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<div id="changethis" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Dropdown <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li id="clickme"><a href="#">Link1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</div>
Further Reading:
You can also check out my answer to Keep Bootstrap Dropdown Open When Clicked Off
Upvotes: 2