Reputation: 581
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!!
Upvotes: 0
Views: 1874
Reputation: 9130
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';
}
}
window.addEventListener('scroll',function(){
scrollChange('sticky');
});
<div id="sticky" style="position:fixed;top:0px;line-height:2em;background:#fff">
Sticky title (0)
</div>
<div style="margin-top:3em;line-height:3em">
<p>This</p><p>is</p><p>just</p><p>padding</p><p>to</p>
<p>test</p><p>scrolling</p><p>down</p><p>the</p>
<p>page</p><p>and</p><p>this</p><p>is</p><p>more</p>
<p>padding</p><p>to</p><p>test</p><p>scrolling</p>
<p>down</p><p>the</p><p>page</p>.</div>
Upvotes: 2