I have structured the page with a header at the top and 3 columns below. The left column contains a menu, the middle column is a text container, and the right column is another section.
As the page scrolls up, the menu becomes fixed in position which functions correctly.
Issue: While scrolling up, each menu should be highlighted (Scroll Spy), but only the last menu is highlighted.
Please provide assistance!
View the sample on jsfiddle
JS
$(function () {
$(window).on('scroll', function (event) {
var scrollValue = $(window).scrollTop();
if (scrollValue > 100) {
$('#spy').addClass('affix');
var elemts = $('.scroll-section');
elemts.each(function(index) {
var id = $(this).attr('id');
console.log(id)
var navElem = $('a[href="#' + id + '"]');
navElem.addClass('active').parent().siblings().children().removeClass( 'active' );
})
}
else{
$('#spy').removeClass('affix');
}
});
});
CSS
.header {
width: 100%;
height: 100px;
background: yellow;
}
.affix {
position: fixed;
top: 0;
}
#spy {
position: fixed;
}
.right-side {
background: gray;
height: 120px;
}
HTML
<body>
<div class="header">
</div>
<div class="row">
<div class="col-sm-3">
<div id="spy">
<ul class="nav nav-pills flex-column">
<li class="nav-item">
<a class="nav-link" href="#scroll1">First Section</a> </li>
<li class="nav-item">
<a class="nav-link" href="#scroll2">Second Section</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#scroll3">Third Section</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#scroll4">Fourth Section</a>
</li>
</ul>
</div>
</div>
<div class="col-sm-7">
<div class="scroll-section" id="scroll1">
<h2>First Section</h2>
<p>
During Compile time, the compiler converts the source code into Microsoft Intermediate Language (MSIL). Microsoft Intermediate Language (MSIL)
...
</p>
</div>
<div class="scroll-section" id="scroll2">
<h2>Second Section</h2>
<p>
...
</p>
</div>
<div class="scroll-section" id="scroll3">
<h2>Third Section</h2>
<p>
...
</p>
</div>
<div class="scroll-section" id="scroll4">
<h2>Fourth Section</h2>
<p>
...
</p>
</div>
</div>
<div class="col-sm-2">
<div class="right-side">
</div>
</div>
</div>
</body>