Affix in Bootstrap

Goud.Kv
Posted by in Bootstrap category on for Intermediate level | Points: 250 | Views : 9280 red flag

Bootstrap is developed by Twitter Inc, and comes with predefined CSS and JavaScript. By using Bootstrap, we can design a very responsive website easily. It is very handy once you understand.
Recommendation
Read ScrollSpy in Bootstrap before this article.

Introduction

Please read Bootstrap Introduction if you are new to Bootstrap.
so far we have seen ScrollSpy in Bootstrap, and now lets see Affix in this artic.

Background

The main objective of this article is to learn the concept of Affix and its uses in Bootstrap.

Using Bootstrap code

At first, lets see how to add Affix class of Bootstrap to our HTML with the below code,
<div data-spy="affix" data-offset-top="60" data-offset-bottom="200">
    <ul class="nav nav-pills">
        <li class="active"><a data-toggle="tab" href="#one">Section One</a></li>
        <li><a data-toggle="tab" href="#two">Section Two</a></li>
        <li><a data-toggle="tab" href="#three">Section Three</a></li>
    </ul>
    <div class="tab-content">
        <div id="one" class="tab-pane fade in active">
            <h1>Welcome to the First section</h1>
        </div>
        <div id="two" class="tab-pane fade">
            <h1>Welcome to the Second section</h1>
        </div>
        <div id="three" class="tab-pane fade">
            <h1>Welcome to the Third section</h1>
        </div>
    </div>
</div>
The above will gives the following output in your browser,

This is something like Tabs that we have seen before.

Using JavaScript:
We can also use the Bootstrap's JavaScript to create Affix as below,
<script type="text/javascript">
    $(document).ready(function () {
        $("#navAffix").affix({
            offset: {
                top: 140, bottom: 200
            }
        });
    });
</script>
And your HTML as,
<div id="navAffix">
    <ul class="nav nav-pills">
        <li class="active"><a data-toggle="tab" href="#one">Section One</a></li>
        <li><a data-toggle="tab" href="#two">Section Two</a></li>
        <li><a data-toggle="tab" href="#three">Section Three</a></li>
    </ul>
    <div class="tab-content">
        <div id="one" class="tab-pane fade in active">
            <h1>Welcome to the First section</h1>
        </div>
        <div id="two" class="tab-pane fade">
            <h1>Welcome to the Second section</h1>
        </div>
        <div id="three" class="tab-pane fade">
            <h1>Welcome to the Third section</h1>
        </div>
    </div>
</div>
This combination will gives the same output as above i.e,


Affix Demonstration:
Now see the clear picture of Affix here. Please add below Style sheet to your view,
<style>
    ul.affix {
        position: fixed;
        top: 0px;
        left: 50px;
        width: 200px;
    }
    ul.affix-top {
        position: static;
    }
    ul.affix-bottom {
        position: relative;
    }

    /* First level of nav */
    .sidenav {
        margin-top:50px;
        padding: 10px;
        background-color: #f1f1f1;
        border-radius: 6px;
        border: 1px solid #0094ff;
    }

    /* All levels of nav */
    .sidebar .nav > li > a {
        display: block;
        color: #0094ff;
    }
    .sidebar .nav > li > a:hover,
    .sidebar .nav > li > a:focus {
        text-decoration: none;
        background-color: #ffffff;
    }
       
    /* Nav: second level */
    .sidebar .nav .nav {
        margin-bottom: 10px;
    }
    .sidebar .nav .nav > li > a {
        padding-top: 3px;
        padding-bottom: 3px;
        padding-left: 25px;
        font-size: 90%;
    }
    #sections {
        background-color:#f1f1f1;
    }
</style>
Dont get confused from above Style sheet as we are using them in the below code.
<div data-spy="scroll" data-target="#navAffix">
    <div class="container">
    <div class="jumbotron">
        <h1>Bootstrap Affix</h1>
    </div>
        <div class="row">
            <nav id="navAffix" class="sidebar col-md-2">
                <ul class="nav sidenav" data-spy="affix" data-offset-top="200">
                    <li class="active">
                        <a href="#education"><strong>Education</strong></a>
                        <ul class="nav">
                            <li><a href="#dotnetfunda">DotNetFunda</a></li>
                            <li><a href="#itfunda">ITFunda</a></li>
                            <li><a href="#kidsfunda">KidsFunda</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="#sports"><strong>Sports Zone</strong></a>
                        <ul class="nav">
                            <li><a href="#football">FootBall</a></li>
                            <li><a href="#cricket">Cricket</a></li>
                            <li><a href="#hockey">Hockey</a></li>
                            <li><a href="#tennis">Tennis</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>

            <div id="sections" class="col-md-10">
                <article id="education">
                    <h2><a href="#">Education</a></h2>
                    <div id="dotnetfunda"><h3>DotNetFunda.Com</h3><strong>DotNetFunda</strong> is a popular online tutorials and guide for latest Microsoft® technologies aimed for beginners and intermediate level professionals. We help beginners to become intermediate level professionals and help intermediate level professionals to become an expert. By following our different sections regularly, we hope you will soon become one of the 'Most Valuable' professional and start shining in your career.</div>
                    <div id="itfunda"><h3>ITFunda.Com</h3><strong>ITFunda</strong> is an e-commerce website that furnishes a platform to the interested buyer and seller to interact and transact for the software or software related services. We typically host study materials, software products / services for buying/selling. This website has been brought to you by IT Funda Corporation, a parent establishment of a popular Microsoft(R) technology related knowledge based website www.dotnetfunda.com.</div>
                    <div id="kidsfunda"><h3>KidsFunda.Com</h3><strong>KidsFunda</strong> is an entertainment website for kids with learning fundamentals to improve their skills and knowledge.</div>
                </article>
                <br />
                <article id="sports">
                    <h2><a href="#">Sports</a></h2>
                    <div id="football">
                        <h3>FootBall</h3>
                        <p>
                            <strong>Football</strong> refers to a number of sports that involve, to varying degrees, kicking a ball with the foot to score a goal. The most popular of these sports worldwide is association football, more commonly known as just "football" or "soccer". Unqualified, the word football applies to whichever form of football is the most popular in the regional context in which the word appears, including association football, as well as American football, Australian rules football, Canadian football, Gaelic football, rugby league, rugby union,[1] and other related games. These variations of football are known as football codes.
                        </p>
                    </div>
                    <div id="cricket">
                        <h3>Cricket</h3>
                        <p>
                            <strong>Cricket</strong> is a bat-and-ball game played between two teams of 11 players each on a field at the centre of which is a rectangular 22-yard long pitch. Each team takes its turn to bat, attempting to score runs, while the other team fields. Each turn is known as an innings.
                        </p>
                        <p>
                            The bowler delivers the ball to the batsman who attempts to hit the ball with his bat away from the fielders so he can run to the other end of the pitch (which is counted as one run) without getting run out (the event in which the fielder throws the ball directly onto wickets or to a player who is near to wickets so he can dislodge them from the ground before the batsman or the non-striker has reached the crease). Each batsman (the other is called non-striker) continues batting until he is out. The batting team continues batting until ten batsmen are out or specified number of overs (defined as 6 countable balls bowled) have been bowled, at which point the teams switch roles and the fielding team comes in to bat.
                        </p>
                    </div>
                    <div id="hockey">
                        <h3>Hockey</h3>
                        <p>
                            <strong>Hockey</strong> is a family of sports in which two teams play against each other by trying to maneuver a ball or a puck into the opponent's goal using a hockey stick. In many areas, one sport (typically field hockey or ice hockey[1]) is generally referred to simply as hockey.
                        </p>
                        <p>
                            The first recorded use of the word "hockey" is from the 1773 book Juvenile Sports and Pastimes, to Which Are Prefixed, Memoirs of the Author: Including a New Mode of Infant Education, by Richard Johnson (Pseud. Master Michel Angelo), whose chapter XI was titled "New Improvements on the Game of Hockey".[2] The belief that hockey was mentioned in a 1363 proclamation by King Edward III of England is based on modern translations of the proclamation, which was originally in Latin and explicitly forbade the games "Pilam Manualem, Pedivam, & Bacularem: & ad Canibucam & Gallorum Pugnam". The English historian and biographer John Strype did not use the word "hockey" when he translated the proclamation in 1720.
                        </p>
                    </div>
                    <div id="tennis">
                        <h3>Tennis</h3>
                        <p>
                            <strong>Tennis</strong> is a sport people play individually against a single opponent (singles) or between two teams of two players each (doubles). Each player uses a racquet that is strung with cord to strike a hollow rubber ball covered with felt over or around a net and into the opponent's court. The object of the game is to play the ball in such a way that the opponent is not able to play a good return.
                        </p>
                        <p>
                            Tennis is an Olympic sport and is played at all levels of society and at all ages. The sport can be played by anyone who can hold a racquet, including wheelchair users. The modern game of tennis originated in Birmingham, England, in the late 19th century as "lawn tennis".[1] It had close connections both to various field ("lawn") games such as croquet and bowls as well as to the older racquet sport of real tennis. During most of the 19th-century in fact, the term "tennis" referred to real tennis, not lawn tennis: for example, in Disraeli's novel Sybil (1845), Lord Eugene De Vere announces that he will "go down to Hampton Court and play tennis."[2]
                        </p>
                    </div>
                </article>
            </div>
        </div>
    </div>
</div>
Run this code in your browser and you will see the following output,


Now scroll down and see the change because of Affix,


And also if you select any content, The side nav will be fixed and not scrolled down.


That is the use of Affix in Bootstrap.

Events of Affix:
Below list are the Events of Affix in Bootstrap which are used in different scenarios.
Event typeDescription
affix.bs.affixThis event fires immediately before the element has been affixed.
affixed.bs.affixThis event is fired after the element has been affixed.
affix-top.bs.affixThis event fires immediately before the element has been affixed-top.
affixed-top.bs.affixThis event is fired after the element has been affixed-top.
affix-bottom.bs.affixThis event fires immediately before the element has been affixed-bottom.
affixed-bottom.bs.affixThis event is fired after the element has been affixed-bottom.

Conclusion

In this article, we have seen Affix in Bootstrap. Hope you understand. If you have any doubts in this topic, please ask below.

Thanks for reading.

Regards,
Krishna.



Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 7/9/2014 | Points: 25
What is Affix and in which scenarios we can use it. How it is different than tabs? Please explain.

Thanks
Posted by: Goud.Kv on: 7/7/2014 | Points: 25
Hello Sir.,

Affix is used to fix the position of section or an element and to toggle its state.
we can use it while scrolling as i explained above in which it changes the position of the side bar on scrolling.
Affix is just a class with position property of CSS', where tabs are used to switch the sections with data-targets.

Thanks,
Krishna.

Login to post response

Comment using Facebook(Author doesn't get notification)