JSFiddle - React, Tailwind, and code Playground
HTML
<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>
CSS
body {
font-family: sans-serif;
}
.section {
height: 100px;
margin-bottom: 50px;
border-radius: 10px;
background-color: #ccc;
color: #555;
text-align: center;
line-height: 100px;
}
#message {
position: fixed;
padding: 10px;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(0, 0, 0, .6);
color: #fff;
transition: all 0.3s ease-out;
}
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;
}
}
// See https://stackoverflow.com/a/125106/5862990
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight) &&
(left + width) <= (window.pageXOffset + window.innerWidth)
);
}