highlighting current section on scroll - gap between sections - javascript

I have a page with different sections that can be scrolled to or accessed by clicking the corresponding link in the navbar. A demo of the page is on codepen http://codepen.io/meek/pen/NNprYb?editors=1010
I am using the following code to keep track of which section the user is scrolling over and highlighting it in the navbar
$(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 && section.position().top + section.height() > currentPos) {
$('.nav li').removeClass('active');
sectionLink.parent().addClass('active');
}
else {
sectionLink.parent().removeClass('active');
}
});
});
It works fine, but there is a gap where scrolling through between home and about sections, none of the links are highlighted. I have a feeling this might be because of the space the navbar occupies between home and about, but I'm not sure how to overcome this. Ideally, I'd like to have that gap also highlight "about".
I've tried to add this to the above code:
else if($('#nav-wrapper').position().top <= currentPos && $('#nav-wrapper').position().top + $('#nav-wrapper').height() > currentPos) {
$('.nav li').removeClass('active');
$('#temp').addClass('active');
}
but it doesn't work. Help appreciated

Solution:
Adjust your if statement in your scroll event to match the following.
if(section.position().top <= currentPos && sectionLink.offset().top + section.height() > currentPos)
The key being, the second instance of section.position().top changes to sectionLink.offset().top

Related

How to change the 'sections' to changeable class or id?

I have this well working code for my onepager, and need to change the target on this. How can I change 'sections' to any class or id?
I tried to add a class like ('.target') but it did not work.
var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
I need this code to work with class or id to have different targets than sections.
Other solution for me could be also: To add something like (top: -100px;) on scrolling. I have a fixed navigation bar and need the script to leave space on top.

Add selected class on scroll at last item

Add selected class on page scroll(not on click) at last item, other item selections are working. For more see
My Script to add selected class on page scroll.
//Selected Using Scroll
$(window).scroll(function () {
var scrollPosition = $(document).scrollTop();
$('#side-nav-id .scrollTo').each(function () {
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
if (refElement.position().top <= scrollPosition + 100) {
$('#side-nav-id .scrollTo').removeClass("selected");
currentLink.addClass("selected");
}
else{
currentLink.removeClass("selected");
}
});
});
My guess is that the last section title is never reaching the position limit you've established with...
if (refElement.position().top <= scrollPosition + 100) {
... because of the content length (is not enough to allow the title to reach that point)
I supposed this is a common problem with this behaviour, because if you have short sections, the last ones will never reach the top.
Some options you could use...
Put the limit down, so your last section reach it. Not very cool, because if the last section is very short, you'd have to put the limit superlow, so the whole behaviour breaks.
Add padding at the end of the container to allow the scroll continue until the last section reach that limit.
Add some 'else' to check if your're at the bottom of the page and in that case highlight the last menu item. Something like...
else if($(window).scrollTop() + $(window).height() == $(document).height()) {
I hope it helps

How to keep class active when scrolling with javascript?

I need help figuring out what is going on with my javascript. I have some code that is supposed to make the nav links have an active class when you are on that part of the page, but it's only sort of working for a couple links and it also flickers as you scroll rather than staying active the whole time you're on that part of the page. See the JSFiddle for an example https://jsfiddle.net/7szpuqsr/ -- if you scroll slowly you can see how "home" becomes active for a moment. I am trying to get each link to have the active class when you click it and also while you are on that entire part of the page.
I also have a javascript sticky nav bar and smooth scrolling working so I don't know if possibly any of that is getting in the way? Thanks in advance for help.
Here's the Javascript I'm trying to use for the active class:
var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
nav.find('a').on('click', function () {
var $el = $(this)
, id = $el.attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top - nav_height
}, 500);
return false;
});
Something like this? I couldn't reproduce the flickering visually on my machine but I can see the class being removed/added constantly on scroll
https://jsfiddle.net/7szpuqsr/1/
Main changes, I added a class to your sections, you have too many sections but with the way your code is meant to work, it's much easier to add a class to the sections, example below
<section id="home" class="section">
var sections = $('.section') to get the section class
updated this part of the js to check for active class
if (cur_pos >= top && cur_pos <= bottom) {
if(!$(this).hasClass("active")) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
}
You can also cache the $(this) into a variable inside of the section loop like
var $this = $(this);
then just use $this for the rest of the loop
here is the doc for hasClass https://api.jquery.com/hasclass/

How to make a navigation sticky when it reached to another top nav

I have two navigation one is on the top and another is in content. I try to make the second sub menu as sticky when it reached to the top menu not the very top offset of browser. But i failed to make it sticky when it scrolled to top. Also how can I add class on on menu item when active 'href' scrolling.
JSfiddle Here
JS Code
$(document).ready(function() {
var $filter = $('.denpen-menu');
var $filterSpacer = $('<div />', {
"class": "filter-drop-spacer",
"height": $filter.outerHeight()
});
if ($filter.size())
{
$(window).scroll(function ()
{
if (!$filter.hasClass('navbar-fixed') && $(window).scrollTop() > $filter.offset().top)
{
$filter.before($filterSpacer);
$filter.addClass("navbar-fixed");
}
else if ($filter.hasClass('navbar-fixed') && $(window).scrollTop() < $filterSpacer.offset().top)
{
$filter.removeClass("navbar-fixed");
$filterSpacer.remove();
}
});
}
});
First we should fetch the starting position of our subNavand store it as "startingPoint"
var startingPoint = $('.stuckMenu').offset().top - 48;
Notice the - 48 part, that's about the height of our main navigation, and a bit less just so it feels better when they touch.
The key part of the logic is this part here:
if (!subNav.hasClass('navbar-fixed') && $(window).scrollTop() > startingPoint)
{
$filter.addClass("navbar-fixed");
}
else if(subNav.hasClass('navbar-fixed') && $(window).scrollTop() < startingPoint)
{
$filter.removeClass("navbar-fixed");
}
Where we ask:
Is our subNav sticky yet? Is the top of the window touching it currently?
Ok its not sticky yet but the window touched it, make it sticky - fixed.
Ok so our subNav is sticky, is the top of the window above the original position of our subNav?
It is above? Ok I do not want it to be sticky any more, so we'll just remove the class.
Check out the example here

Image highlight (hover state) on active section while scrolling?

I have these icons above each section on my page (the largish circular icons, please see example: http://pftest.fhero.net) with colored hover states... what I would really love to do is have them change to the active hover states as the user scrolls to each section (preferably with a simple fade transition) - much like the effect of highlighting the active links/section in the navigation.
There are many tutorials, plugins and questions on this site and so forth for highlighting active sections in a navigation however, but doesn't seem to be much that I can find relating to applying the effect to another div or image on the page...
I'm definitely not any kind of jQuery expert but I'm wondering if one of the myriad of scripts/plugins available which are typically used for highlighting active states in navigation could simply be adapted to this scenario somehow to achieve the same effect? Perhaps even the one I am currently using on my page?
Here is the script I'm using for highlighting the active section in the navigation on my page:
/* Scroll Navigation highlight */
$("#work-section1").parent().addClass('active');
var main = main = $('#mainmenu ul');
$('.scroll').click(function(event) {
event.preventDefault();
var full_url = this.href,
parts = full_url.split('#'),
trgt = parts[1],
target_offset = $('#'+trgt).offset(),
target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
/* Remove active class on any li when an anchor is clicked */
main.children().removeClass();
/* Add active class to clicked anchor's parent li */
$(this).parent().addClass('active');
});
$(window).scroll(function(event) {
if($("#work-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#work-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#footer-section").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
if($("#about-section").offset().top < $(window).scrollTop() + $(window).outerHeight()) {
$("#about-section1").parent().addClass('active');
$("#work-section1").parent().removeClass('active');
$("#footer-section1").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
if($("#services-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#services-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#work-section1").parent().removeClass('active');
$("#footer-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
if($("#process-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#process-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#work-section1").parent().removeClass('active');
$("#footer-section1").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
}
if($("#footer-section").offset().top < $(window).scrollTop() + $(window).outerHeight()){
$("#footer-section1").parent().addClass('active');
$("#about-section1").parent().removeClass('active');
$("#work-section1").parent().removeClass('active');
$("#services-section1").parent().removeClass('active');
$("#process-section1").parent().removeClass('active');
}
});
and the HTML:
<nav id="mainmenu" name="mainmenu">
<ul>
<li><a class="scroll" id="work-section1" href="#work-section">Works</a></li>
<li><a class="scroll" id="about-section1" href="#about-section">About</a></li>
<li><a class="scroll" id="services-section1" href="#services-section">Services</a></li>
<li><a class="scroll" id="process-section1" href="#process-section">Process</a></li>
<li><a class="scroll" id="footer-section1" href="#footer-section">Contact</a></li>
</ul>
</nav>
<section id="about-section" data-anchor-offset="90">
<section id="work-section" data-anchor-offset="90">
...ect...
Could this somehow be adapted to accomplish the effect I am looking for? Or any other/better methods, or plugins I should be looking at?
I should add that the icons use the sprites method which could make the CSS side of things a little trickier, although I would be willing to change them to non-sprite images if necessary...
You could use a small little function for this, that checks if a element is on screen. I set up a little JSFiddle for you: http://jsfiddle.net/LHrkB/1/
Code:
function isElementVisible(elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = $(elementToBeChecked).offset().top;
var BotElement = TopElement + $(elementToBeChecked).height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
$(window).scroll(function () {
isOnView = isElementVisible(".inview");
if(isOnView){
//What to do when element is visible
$(".inview").css({"background":"#ccc"});
}else{ // If not visible
}
});
Ok, so i have changed the JSFiddle a bit, now it uses a fadeIn on a invisible element when it comes into view: http://jsfiddle.net/LHrkB/2/
Ok, i changed the JSFiddle once again. When you scroll in the results pane, and you play around with it a bit you can see the element change class as it comes on screen and also when it goes away again. I commented the JS so you can see what it does and where it does it. http://jsfiddle.net/LHrkB/4/
Thanks to the help of Veritas87 (who is super awesome), managed to get it all working with the following code:
function isElementVisible(elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = $(elementToBeChecked).offset().top;
var BotElement = TopElement + $(elementToBeChecked).height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
$(window).scroll(function () {
isOnView = isElementVisible(".about-icon");
if(isOnView){
//What to do when element is visible
$('.about-icon').addClass('about-icon-active');
}else{ // If not visible
$('.about-icon').removeClass('about-icon-active');
}
isOnView = isElementVisible(".works-icon");
if(isOnView){
//What to do when element is visible
$('.works-icon').addClass('works-icon-active');
}else{ // If not visible
$('.works-icon').removeClass('works-icon-active');
}
isOnView = isElementVisible(".services-icon");
if(isOnView){
//What to do when element is visible
$('.services-icon').addClass('services-icon-active');
}else{ // If not visible
$('.services-icon').removeClass('services-icon-active');
}
isOnView = isElementVisible(".process-icon");
if(isOnView){
//What to do when element is visible
$('.process-icon').addClass('process-icon-active');
}else{ // If not visible
$('.process-icon').removeClass('process-icon-active');
}
});
with the "...icon-active" classes of course containing the style for the icon hover states.

Categories