Highlighting current section in navbar - javascript

I have a scrolling page with a navbar and I want the section the user is scrolling through to be highlighted in the navbar. At the moment it almost accomplishes this, but is highlighting the incorrect link.
A demonstration is at http://codepen.io/meek/pen/NNprYb?editors=1000
The code that does this is as follows:
// highlight current tab
$(window).on("scroll", function() {
var currentPos = $(window).scrollTop();
$('.nav li a').each(function() {
var sectionLink = $(this);
var section = $(sectionLink.attr('href'));
if(section.position().top <= currentPos && sectionLink.offset().top + section.height() >= currentPos) {
$('.nav li').removeClass('active');
sectionLink.parent().addClass('active');
}
else {
sectionLink.parent().removeClass('active');
}
});
});
I've tried several things, but can't get it to reliably add the active class to the correct session. Help appreciated!
edit: to be clearer, the problem is that it's only highlighting the section when you've scrolled a bit into it, instead of right at the top, meaning that when you click a section to scroll to the top of that section automatically, that section is not highlighted.
edit2: So changing the if statement to:
if(currentPos + $('#nav-wrapper').outerHeight() >= section.position().top && currentPos + $('#nav-wrapper').outerHeight() <= sectionLink.offset().top + section.outerHeight()) {
has made an improvement although not completely fixed the issue. The home, about and portfolio sections all highlight the correct link but not contact.

You need to account for the height of the navbar and subtract it from the top of the section you want highlighted.
The height is currently hardcoded in your CSS at 75px but I included a jQuery selector for the height in case it needs to change/disappear for smaller screens.
Nice work by the way.
$(window).on("scroll", function() {
var currentPos = $(window).scrollTop();
$('.nav li a').each(function() {
var sectionLink = $(this);
// capture the height of the navbar
var navHeight = $('#nav-wrapper').outerHeight() + 1;
var section = $(sectionLink.attr('href'));
// subtract the navbar height from the top of the section
if(section.position().top - navHeight <= currentPos && sectionLink.offset().top + section.height()> currentPos) {
$('.nav li').removeClass('active');
sectionLink.parent().addClass('active');
} else {
sectionLink.parent().removeClass('active');
}
});
});

Related

How can I prevent the class being added to the header before scroll takes place

I am trying to use javascript to add a class to my header when the user scrolls, however the class scrollled2 is being added before the scroll takes place.
The code I am using is as follows:
$(document).ready(function() {
var s = $(".site-header");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
if (windowpos >= pos.top & windowpos >=50) {
s.addClass("scrolled2");
} else {
s.removeClass("scrolled2");
}
});
});
I need the effect of the scroll to beging after the first 50px have been scrolled past.
Any help would be appreciated.

Having the same nav bar become fixed after scrolling past a certain element

I currently have a nav bar within my header that I would like to become fixed after the user scrolls past a certain element. I would also like to achieve the same animation effect as seen at http://pixelmatters.com
When I say 'same' I mean using the same nav bar/header element that I'm using at the top, rather than using a duplicate somewhere else in my document.
I've tried to achieve he result with my own code shown below. I've also included a jsFiddle link of my current setup.
jQuery
var bottomElement = $('.dividerWrap').offset().top + $('.dividerWrap').height();
$(window).on('scoll', function() {
var stop = Math.round($(window).scrollTop());
if (stop > bottomElement) {
$('.header').addClass('isFixed');
} else {
$('.header').removeClass('isFixed');
}
});
https://jsfiddle.net/npfc8wsx/1/
I answered something like that few days ago. please take a look at this code:
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
var scrollToVid = $('#test').offset().top
console.log(scrollTop); //see window scroll distance //
console.log(scrollToVid); //see scroll to div offest//
if ($(window).scrollTop() >= scrollToVid) {
alert('You reached to the video!');
}
});
jSFiddle
Main Question
now for you some code must change:
$(window).scroll(function () {
var scrollToElem = $('.dividerWrap').offset().top
if ($(window).scrollTop() >= scrollToElem) {
$('.header').addClass('isFixed');
} else {
$('.header').removeClass('isFixed');
}
});

Adding a CSS class based on browser scroll position with jQuery - looking for a more modular approach

On my current site(uptrde.com) I have it setup to when you scroll to a certain section of the page the nav a that corresponds with that section lights up. However, I feel that the way I am doing it with jQuery is difficult and not modular at all. My code for animating the page scrolls works fine, just this last bit is giving me trouble. I would like to make this code more modular so if I add more sections to the site in the future I don't have to figure out new values. Thank you for your help.
$(window).scroll(function() {
$(".mainNav a").removeClass("selected");
var scroll = $(window).scrollTop();
//add the 'selected' class to the correct id element based on the scroll amount
if (scroll >= 0 && scroll <= 855) {
$("#homeNav").addClass("selected");
} else if (scroll >= 855 && scroll <= 1808) {
$("#aboutNav").addClass("selected");
} else if (scroll >= 1808 && scroll <= 2700) {
$("#sampleNav").addClass("selected");
} else if (scroll >= 2700 && scroll <= 3780){
$("#clientsNav").addClass("selected");
} else {
$("#contactNav").addClass("selected");
}
});
<nav id="menu">
<ul class="mainNav">
<li>Home</li>
<li>About Us</li>
<li>Samples</li>
<li>Clients</li>
<li>Contact</li>
</ul>
</nav>
Here's what I'd recommend. Loop through each of the sections on the page and get the rendered height. Add each of those heights to an array, and then loop through the array when you are adding the classes. Something like this:
$(window).scroll(function(){
var scroll = $(window).scrollTop();
var section_height = new Array();
var section_position = new Array();
$('.main-container').children().each(function(){
section_height.push($(this).height());
section_position.push($(this).offset().top);
});
for(i=0; i<section_position.length; i++){
if($(window).scrollTop() > section_position[i] - (section_height[i] / 4)){
$('.mainNav li').not(':nth-child('+i+')').find('a').removeClass('selected');
$('.mainNav li:nth-child('+i+') a').addClass('selected');
} else {
$('.mainNav li:nth-child('+i+') a').removeClass('selected');
}
}
});
I haven't tested this with your site, but I used the same code on another site earlier today, and it worked like a charm. You'll want to play with the calculation used in the if statement in the for loop. I have it set to change to the next section when you're about 1/4 of the height away from it. In other words, I wanted it to change to the next nav element when you were "almost" to it in the scroll position. I didn't want to have to wait till it was all the way at the top of your screen before changing the highlighted nav element. You, however, may choose to do it differently.
maybe this can help you
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop() + 90;
var currentArea = $('.area').filter(function() {
return scroll <= $(this).offset().top + $(this).height();
});
$('nav a').removeClass('selected');
$('nav a[href=#' + currentArea.attr('id') +']').addClass('selected');
//console.debug('nav a[href=#' + currentArea.attr('id') +']');
});
});
JSFiddle: http://jsfiddle.net/LGzxq/1/

Menu fixed on single page - change color

i want to create a menu for a single page website with link to div from page.
The menu look like this:
<li>Home</li>
...
<div id="home-link"></div>
I want to change color of link from menu when i am in area of home-link div. How is possible to make that thing?
Thanks for answers and for your help.
Have a nice day.
You will need JavaScript for this if the link element is not a child of #home-link.
Something like this:
$('#home-link').on('hover', function () {
$('li a').css('color', '#bada55');
});
This assumes you are using jQuery, but similar approach with other frameworks would work as well.
If I assume from the question that if you are hovering on #home-link and color of anchor should change, then
$('#home-link').hover(function () {
$('li a').css('color', 'red');
});
or if I assume that if the id is present in your page and you want to change the color of the anchor then
if($('#home-link').length){
$('li a').css('color', 'red');
}
I found myself with (what I believe is) the same question: how can I change which navigation link is highlighted to reflect the area I've scrolled to, whether I get there by using the link or just by scrolling down the page?
Here's a page with a very helpful tutorial.
The theory:
We create an array of all our nav a href’s. We then use some calculations using the scroll function. We find the section id, calculate it’s height, see if it’s greater or less than the value from the window top, and if the window falls in between, we add a class nav-active to the list item in question. We create a conditional also, because if the top of a section is not reached and the page can’t scroll anymore, we want to highlight this section.
And the relevant jQuery code:
/**
* 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; // 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("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-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");
}
}
});

Making nav bar effects using scroll AND click in jQuery

I want a nav to highlight (or something similar) once a user clicks on it AND when a user scrolls to the corresponding section.
However, on my computer when one clicks on any of the nav events after3, only nav event 3 changes. I'm guessing this is because after one clicks on 4 or 5, the scroll bar is already at the bottom of the page, so 4 and 5 never reach the top. The only div at the top is post 3, so my code highlights nav event 3 and ignores the click.
Is there any way I can fix this? Ive tried if statements (only highlight nav event if it's at the top AND the scrollbar isn't at the bottom or the top isn't the last item).
Here is a more accurate fiddle, using a fix below showing what I am talking about. The fix now highlights on scroll, but if you click option 5, it will not highlight.
$('.option').children('a').click(function() {
$('.option').css('background-color', '#CCCCCC;');
$(this).css('background-color', 'red');
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$(window).scrollTop(postLocation);
});
$(window).scroll(function() {
var scrollBar = $(this).scrollTop();
var allPosts = [];
var post = $('.content').offset();
var lastPost = allPosts.legnth-1
var windowHeight = $(window).height();
var bottomScroll = windowHeight-scrollBar;
$(".content").each(function(){
allPosts.push($(this).attr('id'));
});
i = 0;
for(i in allPosts){
var currentPost = "#"+allPosts[i];
var postPosition = $(currentPost).offset().top;
if (scrollBar >= postPosition){
$('.option').css('background-color', '#CCCCCC');
$('#nav'+allPosts[i]).css('background-color', 'red');
};
};
});
I think you've overdone your scroll() handler, to keep it simple you just needs to check if the scrollbar/scrollTop reaches the '.contents' offset top value but should not be greater than its offset().top plus its height().
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
$(".content").each(function (index) {
var elTop = $(this).offset().top;
var elHeight = $(this).height();
if (scrollBar >= elTop - 5 && scrollBar < elTop + elHeight) {
/* $(this) '.content' is the active on the vewport,
get its index to target the corresponding navigation '.option',
like this - $('.Nav li').eq(index)
*/
}
});
});
And you actually don't need to set $(window).scrollTop(postLocation); because of the default <a> tag anchoring on click, you can omit that one and it will work fine. However if you are looking to animate you need first to prevent this default behavior:
$('.option').children('a').click(function (e) {
e.preventDefault();
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$('html, body').animate({scrollTop:postLocation},'slow');
});
See the demo.
What you are trying to implement from scratch, although commendable, has already been done by the nice folks at Bootstrap. It is called a Scrollspy and all you need to do to implement it is include Bootstrap js and css (you also need jquery but you already have that) and make some minor changes to your html.
Scrollspy implementation steps.
And here is a demonstration. Notice only one line of js. :D
$('body').scrollspy({ target: '.navbar-example' });

Categories

Resources