Diego Burela Diego Burela -4 years ago 41
Javascript Question

In Bootstrap's dropdown menu with javacript, what is the point of the following code?

Bootstrap's site tell us,


Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the .open class on the parent list item.


In the following code, which is considered to be "via JavaScript" there is the following script:

<script type="text/javascript">
$(document).ready(function(){
$('.myDropdownHandle').dropdown('toggle');
});


I was under the impression that this block of code will be necessary for the dropdown to work if we wanted to toggle "via Javascript" but I can erase that block and the dropdown will still work via the data attributes, but if I erase the data attributes the dropdown won't work at all.

<!DOCTYPE html>
<html lang="en">
<head>
<script type='text/javascript'
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.myDropdownHandle').dropdown('toggle');
});
</script>
</head>
<body style='margin:30px'>
<div class="dropdown" id="myDropdown">
<a class="myDropdownHandle" data-toggle="dropdown" data-target="#" href="#">
Dropdown <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>
</div>

</body>
</html>

Answer Source

This jQuery code will make it so that upon the loading of the page, your dropdown list would be showing, as in, the contents of the drop down list will be visible.

$(document).ready(function(){
    $('.myDropdownHandle').dropdown('toggle');
});

Therefore, if you don't want the dropdown toggled on page load, then remove this piece of code. However if you remove the data attribute, your dropdown will not behave as one.

Reference this W3School Link will further clarify for you. Here is an example which shows the dropdown toggle in action.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download