Fedreg Fedreg - 2 months ago 7x
CSS Question

Change sticky header text depending on distance from top of page

Hi, trying to have the text inside a sticky header change in relation to how far away it is from the top of the page. Supposing I have a single page site, with several distinct did sections each measuring 100vh. The nav links to them via href="#sectionA", "#sectionB", etc.

So if I start on the landing page and scroll down to "sectionA" the header should change to that sections title. Couldn't figure out how to do this using the .href but if that is a preferable way I'm amendable.

Currently have:

function scrollChange(id) {
var winHeight = window.innerHeight;
if (window.scrollBy(winHeight)) {
document.getElementById(title).innerHTML = 'SomethingB';

else if (window.scrollBy(winHeight * 2)) {
document.getElementById(title).innerHTML = 'SomethingC';

else {
document.getElementById(title).innerHTML = 'somethingA';

document.addEventListener('scroll', function() {scrollChange();});

The DOM manipulation doesn't matter for right now; just trying to get the correct reference by scroll. No JQuery answers please. Thank you!!


Complete re-write based on feedback and testing :]

function scrollChange(id) {
    console.log('scroll w.height:['+ window.innerHeight +'] scroll:['+ window.scrollY +']');
    // start with the biggest value first
    if (window.scrollY > (window.innerHeight / 2)) {                                                                   
        document.getElementById(id).innerHTML = 'Something big';                                                       

    } else if (window.scrollY > (window.innerHeight / 3)) {                                                            
        document.getElementById(id).innerHTML = 'Something middle';                                                    

    } else {
        document.getElementById(id).innerHTML = 'Something small';                                                     
<div id="sticky" style="position:fixed;top:0px;line-height:2em;background:#fff">                                       
Sticky title (0)
<div style="margin-top:3em;line-height:3em">