Saturday 18 January 2014

Bootstrap fixed-top-navbar: Solving the challenge of having Links within page position correctly


  This is more or less a Bootstrap primer. There were different solutions available, but the basic issue was that off the Title of the link hiding itself under the navbar. My header went and hid itself under the navbar as shown in picture.


The usual technique as advised by Bootstrap was to have padding in the body when adding fixed-top-navbar. But that would not work in this case unfortunately. Also having a big padding to offset the navbar for every heading would create lot more spacing than I would like to have. 

The solution which worked for me was to add spacing as and when the user clicks the link to navigate to that section. I used a mix of jQuery and CSS magic for this along with slightly changing the way I wrote the HTML. I made changes so that a jQuery function can formulate the id dynamically from the button name itself. In my case I just removed the white spaces and hey presto!.. I have the id to the section where I need to go to :-).

First of all I enclosed my header tags into another div and put it under page-header class. This is a class which is available in the Bootstrap itself. But I believe you can put any arbitrary class which suits the structure. 

The next step is to make the css for the "active" page-header ( which is the one clicked by user ) have a padding which would show title below the navbar. So i created a rule in CSS so that the "page-header active" would have enough spacing. 
The last stage is to have a jQuery function call onto the anchor/button click event so that it does some magic. The steps done are
(i) Remove the active tag from all the buttons of the same class.
(ii) Set the active tag to the button on which click event has registered
(iii)  Parse the name of the button and form the target id.
(iv) Set the padding of destination
(v) Go to location using jQuery
This worked for me elegantly, hope this helps you too or gives ideas to have more amazing stuff created.

No comments:

Post a Comment