ScrollSpy in Bootstrap

Goud.Kv
Posted by in Bootstrap category on for Intermediate level | Points: 250 | Views : 5648 red flag
Rating: 5 out of 5  
 1 vote(s)

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 Carousel Sliders in Bootstrap before this article.

Introduction

Please read Bootstrap Introduction that explains how to include Bootstrap in your project if you are new to Bootstrap.
Twitter Bootstrap consists of predefined JavaScript to create ScrollSpys.

Objective

The main objective of this article is to learn different types of creating ScrollSpys using Bootstrap.

Using Bootstrap code

Please add the below Style code in your page first in order to understand the ScrollSpy easily.
<style>
    .scrollspy-example {
        height:250px;
        overflow:auto;
        position:relative;
    }
</style>
You will get it soon of adding above style in our page.
Now lets go and create some sections with ScrollSpy like in the below example code,
<div>
    <nav id="navbarScroll" class="navbar navbar-inverse" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-scrollspy">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">ScrollSpy</a>
            </div>
            <div class="collapse navbar-collapse navbar-scrollspy">
                <ul class="nav navbar-nav">
                    <li><a href="#Dnf">DotNetFunda</a></li>
                    <li><a href="#Itf">ITFunda</a></li>
                    <li class="dropdown">
                        <a href="#" id="navbarDrop1" class="dropdown-toggle" data-toggle="dropdown">Sports <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu" aria-labelledby="navbarDrop1">
                            <li><a href="#football" tabindex="-1">FootBall</a></li>
                            <li><a href="#cricket" tabindex="-1">Cricket</a></li>
                            <li class="divider"></li>
                            <li><a href="#hockey" tabindex="-1">Hockey</a></li>
                            <li><a href="#tennis" tabindex="-1">Tennis</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div data-spy="scroll" data-target="#navbarScroll" data-offset="0" class="scrollspy-example">
        <h1>Education:</h1>
        <hr />
        <h3 id="Dnf">DotNetFunda</h3>
        <p>
            DotNetFunda.Com 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.
        </p>
        <h3 id="Itf">ITFunda</h3>
        <p>
            ITFunda.Com 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.
        </p>

        <h1>Sports:</h1>
        <hr />
        <h3 id="football">FootBall</h3>
        <p>
            <b>Football</b> 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>
        <h3 id="cricket">Cricket</h3>
        <p>
            <b>Cricket</b> 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>
        <h3 id="hockey">Hockey</h3>
        <p>
            <b>Hockey</b> 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>
        <h3 id="tennis">Tennis</h3>
        <p>
            <b>Tennis</b> 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>
</div>
Do not get confused with the above code as we are using the navbar which we already seen in here. The important things are, we have to give the data-targets correctly and also need to set the perfect matches of ID's.
Now, run this code in your browser to see the output as follows,

If you click on the ITFunda option in the navbar, you will be able to see the ITFunda section like below,

And if you go to 'Sports' and select any sport, then also you will get the corresponding section such as,


Using JavaScript:

Below JavaScript is used to create the ScrollSpy,
<script type="text/javascript">
    $(document).ready(function () {
        $(".scrollspy-example").scrollspy({ target: "#navbarScroll" })
    });
</script>
scrollspy is the Inbuilt method from Bootstrap's JavaScript.

Creating ScrollSpy with Events of JavaScript:
We have some more functionalities such as refresh, remove etc. which are shown in the below script,
<script type="text/javascript">
    $(document).ready(function () {
        removeThis = function (e) {
            $(e).parents(".section").remove();
            $('[data-spy="scroll"]').each(function () {
                var $spy = $(this).scrollspy('refresh')
            });
        }
        $(".scrollspy-example").scrollspy({ target: "#navbarScroll" });
    });
</script>
In the above script, we are using remove function which is used to remove a part or a section temporarily.

Add the below HTML along with this script,
<div>
    <nav id="navbarScroll" class="navbar navbar-inverse" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-scrollspy">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">ScrollSpy</a>
            </div>
            <div class="collapse navbar-collapse navbar-scrollspy">
                <ul class="nav navbar-nav">
                    <li><a href="#Dnf">DotNetFunda</a></li>
                    <li><a href="#Itf">ITFunda</a></li>
                    <li class="dropdown">
                        <a href="#" id="navbarDrop1" class="dropdown-toggle" data-toggle="dropdown">Sports <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu" aria-labelledby="navbarDrop1">
                            <li><a href="#football" tabindex="-1">FootBall</a></li>
                            <li><a href="#cricket" tabindex="-1">Cricket</a></li>
                            <li class="divider"></li>
                            <li><a href="#hockey" tabindex="-1">Hockey</a></li>
                            <li><a href="#tennis" tabindex="-1">Tennis</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div data-spy="scroll" data-target="#navbarScroll" data-offset="0" class="scrollspy-example">
        <h1>Education:</h1>
        <hr />
        <div class="section">
            <h3 id="Dnf">DotNetFunda <small><a href="#" onclick="removeThis(this)">Remove</a></small></h3>
            <p>
                DotNetFunda.Com 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.
            </p>
        </div>
        <div class="section">
            <h3 id="Itf">ITFunda <small><a href="#" onclick="removeThis(this)">Remove</a></small></h3>
            <p>
                ITFunda.Com 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.
            </p>
        </div>

        <h1>Sports:</h1>
        <hr />
        <div class="section">
            <h3 id="football">FootBall <small><a href="#" onclick="removeThis(this)">Remove</a></small></h3>
            <p>
                <b>Football</b> 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 class="section">
            <h3 id="cricket">Cricket <small><a href="#" onclick="removeThis(this)">Remove</a></small></h3>
            <p>
                <b>Cricket</b> 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 class="section">
            <h3 id="hockey">Hockey <small><a href="#" onclick="removeThis(this)">Remove</a></small></h3>
            <p>
                <b>Hockey</b> 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 class="section">
            <h3 id="tennis">Tennis <small><a href="#" onclick="removeThis(this)">Remove</a></small></h3>
            <p>
                <b>Tennis</b> 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>
    </div>
</div>
 Above HTML code is similar to the example we have seen earlier in this chapter in which adding the remove functions to different sections.
This combination will give you the output something like below,
Observe the above output that, we can remove the sections temporarily by clicking on 'Remove'.

We have set 'Remove' function to all the sections i.e,


Displaying Current Status:
We can also display the status of the current section. For that, please add the below script and a HTML tag to the above code,
<script type="text/javascript">
    $(document).ready(function () {
        $("#navbarScroll").on("activate.bs.scrollspy", function () {
            var currentView = $(".nav li.active > a").text();
            $("#show").empty().html("Currently you are at - " + currentView);
        });
    });
</script>
 'active.bs.scrollspy' is the predefined bootstrap Event which is responsible to get the current state of the ScrollSpy.
<h3 id="show" class="text-success">Currently you are at - DotNetFunda</h3>
Now, adding the above tag with 'show' id from above JavaScript will makes the script work in your page.

If you add these code to your page and run, You will see the Current state of ScrollSpy like in the below output,


Try going to different sections like below,

So., you will get the Current state of the ScrollSpy for all the sections.

Conclusion

In this article, we have seen different types of ScrollSpys in Bootstrap. Hope you understand. If you have any doubts in this topic, please ask in the below comment box.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read Affix in Bootstrap after this article.
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

Login to post response

Comment using Facebook(Author doesn't get notification)