I'm using the basic Twitter Bootstrap navbar for my menu, and I now want to show notifications in a dropdown inspired by the system here on Stackoverflow. To accomplish this I want to call the api when clicking the dropdown, for which I need to "catch" the dropdown event. According to the docs, I need to catch the event like so:
$('#myDropdown').on('show.bs.dropdown', function () {
// do something…
})
So I've got a working fiddle here, but when I use the exact same code in my own html (see below) it doesn't work anymore. Does anybody know what's wrong with the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- jQuery -->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- Bootstrap -->
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
$('#jajaja').on('show.bs.dropdown', function () {
alert('Come on lets show the dropdown!!');
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">My Website</a>
</div>
<div id="navbar" class="navbar-collapse">
<ul class="nav navbar-nav navbar-right" id="jajaja">
<li class="dropdown">
<a href="" id="notifications-header" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Notifications <span class="caret"></span></a>
<ul id="notifications" class="dropdown-menu" role="menu">
<li><span class="glyphicon glyphicon-refresh text-center" aria-hidden="true"></span></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
This is because you load the javascript code using onload. See the onload selection in the dropdown left.
Because you place the code in the head and you don't wait till the dom is ready.
Check if the dom is ready. Can be done like so:
$(document).ready(function() {
$('#jajaja').on('show.bs.dropdown', function () {
alert('Come on lets show the dropdown!!');
});
});
Or in short:
$(function() {
$('#jajaja').on('show.bs.dropdown', function () {
alert('Come on lets show the dropdown!!');
});
});
Other good practice is placing all javascript just before closing the body </body>
.
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