Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Detecting if section is currently visible on scroll

I am trying to do a sort of navigation based on current section.

My code is as follows:

$(function() {
    'use strict';

    function setTitle(title) {
        $('.overlay').text(title);
    }

    function removeTitle() {
        $('.overlay').text('');
    }

    $(window).on('scroll', function() {
        let windowScroll = $(window).scrollTop(),
            sections = $('section[data-title]');

        sections.each(function() {
            let thisStart = $(this).offset().top,
                thisHeight = $(this).outerHeight(true),
                thisTitle = $(this).attr('data-title'),
                thisEnd = thisHeight + thisStart;

            console.log(`start: ${thisStart}, end: ${thisEnd}, scroll: ${windowScroll}`);

            if(windowScroll >= thisStart && windowScroll < thisEnd) {
                setTitle(thisTitle);
            } else {
                removeTitle();
            }
        });
    });
});

HTML

<section class="section section-first"></section>
<section class="section section-what" data-title="First">
</section>
<section class="section section-cv" data-title="Secound">
</section>
<div class="overlay"></div>

Unfortunately, it works only with last .section. What can I do?

Please refer to my CodePen to see what I mean exactly: http://codepen.io/tomekbuszewski/pen/Xmovwq

Upvotes: 2

Views: 59

Answers (1)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Add return false; here:

if(windowScroll >= thisStart && windowScroll < thisEnd) {
    setTitle(thisTitle);
    return false;        // <- add this
} else {
    removeTitle();
}

That will break out of the each method and prevent the title from being removed once it's been set.

CodePen

Upvotes: 2

Related Questions