Jonathan
Jonathan

Reputation: 641

How to change the menu active link while scrolling?

I want to change the active class on my menu-items when scrolling down. When you scroll to the content that belongs to the menu-link, give that an active state (that will be styled in css). It's the same effect that Bootstrap is using with the scrollspy plugin. However, I'm not using that same setup so I've tried several other scripts but I still can't get it to work. I'm using bootstrap 3 with the following code:

Check out the fiddle

HTML:

<div class="intro"><h1>Please scroll down</h1></div>

<div class="row">

    <div class="col-md-2">
        <div id="menu">
            <ul class="navigation">
                <li><a class="active" href="#one">One</a></li>
                <li><a href="#two">Two</a></li>
                <li><a href="#three">Three</a></li>
                <li><a href="#four">Four</a></li>
                <li><a href="#five">Five</a></li>
                <li><a href="#six">Six</a></li>
                <li><a href="#seven">Seven</a></li>
            </ul>
        </div>
    </div>
    <!-- end of Menu -->

    <!-- Content -->
    <div id="content" class="col-md-10">
        <h2 id="one">One</h2>
        <p class="text"></p>
        <h2 id="two">Two</h2>
        <p class="text"></p>
        <h2 id="three">Three</h2>
        <p class="text"></p>
        <h2 id="four">Four</h2>
        <p class="text"></p>
        <h2 id="five">Five</h2>
        <p class="text"></p>
        <h2 id="six">Six</h2>
        <p class="text"></p>
    </div>

</div>

<div class="footer">
    <h2 id="seven">Seven</h2>
    <p class="text"></p>
</div>

CSS:

body, html {
    height: 100%;
}
.intro {
    min-height: 100%;
    background: olive;
    color: #fff;
    text-align: center;
}
h1, h2 {
    padding: 40px 0 0;
    margin:0;
}
p.text {
    height: 700px;
    background: #ccc;
}
.active {
    background: pink;
}

Upvotes: 4

Views: 6368

Answers (2)

ChaoticNadirs
ChaoticNadirs

Reputation: 2290

You can do the following to get it working with Bootstrap's scrollspy.

Add this CSS to use relative positioning for the body

body{
    position: relative; 
}

Add the following line of JS to specify the scrollspy target.

$('body').scrollspy({ target: '#menu' })

Add the nav class to the menu (scrollspy looks for an element with class nav inside the target).

<ul class="nav navigation">

New fiddle: http://jsfiddle.net/tunwe6we/4/

Upvotes: 7

quead
quead

Reputation: 178

You can use http://api.jquery.com/scroll

$( window ).scroll(function() {
   //yourcode
});

And down you have a demo, btw don't forget to add every element divs like:

<div class="box">
    <h1>H1</h1>
    <p>text</p>
</div>

http://jsfiddle.net/sxsw45fd/15/

I added step by step but you can create function.

I don't know why you want this if you use bootstrap you can simply use scrollspy as @ChaoticNadirs said.

Upvotes: 1

Related Questions