I'm currently working on building my very first single-page website.
If you want to check out the jsfiddle for it, here's the link: http://jsfiddle.net/dgfhjxLt/
The main issue I'm facing is related to the first div section. When a user scrolls through the pages, the link colors should change to indicate which page they're on. This functionality works smoothly for all links except the first one.
Whenever users land on the site initially, the first link should show as active with blue text. However, this only takes effect after scrolling a bit, and then it works as intended.
I've been stuck trying to fix this problem for about an hour now. Surely, there must be a simple solution?
Sharing the jQuery code snippet below:
jQuery(document).ready(function($) {
var offsetHeader = 60;
$('.scroll').click(function(){
var $target = $($(this).attr('href'));
$(this).parent().addClass('active');
$('body').stop().scrollTo( $target , 800, {'axis':'y', offset: -offsetHeader});
return false;
});
/**
* This part handles the highlighting functionality.
* We use the scroll functionality again, some array creation and
* manipulation, class adding and class removing, and conditional testing
*/
var aChildren = $("nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = $(aChild).attr('href');
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop(); // get the offset of the window from the top of page
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
var divPos = $(theID).offset().top-60; // get the offset of the div from the top of page
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("active");
} else {
$("a[href='" + theID + "']").removeClass("active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("nav li:last-child a").addClass("nav-active");
}
}
});
});