Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How navbar-toggle, collapse, navbar-collapse classes work together?

I am new to the world of CSS and Bootstrap 3.0. Below is code which I can find at many places and now I can write it without any problem. But I really don't know how things are working behind the scenes.

<div class="navbar navbar-static-top navbar-inverse" role="navigation">
        <a class="navbar-brand">Company</a>
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".top-nav">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse top-nav">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">News</a></li>
                <li><a href="#">About Us</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </div>
    </div>

Above code will provide me a dynamic UI. Can someone answer my below queries

  1. How connection is established between button and navbar. Ans: In this case I know class named 'top-nave' connect these two components. But then what is significance of other classes ( collapse navbar-collapse ). I have learned that we need to have both the classes i.e. collapse and navbar-collapse. Dont know why?
  2. Is all magic done by CSS or we do have some javascript code that is manipulating code? ( I guess yes since there exists data- attribute)
  3. Can anyone suggest other usage of data-toggle and data-target attribute in bootstrap 3 to understand concept clearly?

Regards, Hemant

like image 336
user2243747 Avatar asked Dec 31 '13 10:12

user2243747


1 Answers

1. Nature of connection between button and navbar:

Through collapse.js. From the v3 documentation,

buttons show and hide another element via class changes:
.collapse hides content
Use a button with the data-target attribute and the data-toggle="collapse".

so in your code, data-target=".top-nav"

The classes collapse and navbar-collapse are significant for the CSS.

Both are needed to allow more specific selectors in the CSS.

2. The navbar collapses using javascript: https://github.com/twbs/bootstrap/blob/v4-dev/js/src/collapse.js

3. The attributes data-toggle and data-target are used throughout bootstrap for things like toggling visibility as discussed, but also in the carousel or to launch modals.

like image 85
TT-- Avatar answered Oct 01 '22 21:10

TT--