It changes the #message
's content by scrolling across sections (.section
) in the page and identifying which one is visible on viewport. Complete code on the link below:
https://jsfiddle.net/hw475zeL/
Markup:
<div class="container">
<h1>Custom message on scrolling</h1>
<div id="section-1" class="section">
<h2>Section 1</h2>
</div>
<div id="section-2" class="section">
<h2>Section 2</h2>
</div>
<div id="section-3" class="section" data-message="Showing section 3">
<h2>Section 3</h2>
</div>
<div id="section-4" class="section" data-message="Showing section 4">
<h2>Section 4</h2>
</div>
<div id="section-5" class="section" data-message="Showing section 5">
<h2>Section 5</h2>
</div>
<div id="section-6" class="section">
<h2>Section 6</h2>
</div>
</div>
<div id="message" style="visibility: hidden; opacity: 0;">Teste</div>
JavaScript:
var sections = document.querySelectorAll('.section');
var message = document.querySelector('#message');
document.onscroll = function(event) {
for (var section of sections) {
if (elementInViewport(section) && section.hasAttribute('data-message')) {
message.innerText = section.getAttribute('data-message');
message.style.visibility = 'visible';
message.style.opacity = 1;
break;
}
message.style.visibility = 'hidden';
message.style.opacity = 0;
}
}
And the elementInViewport()
function from this answer:
https://stackoverflow.com/a/125106/5862990