My Goal
https://i.sstatic.net/JbdXR.gif
I aim to bring attention to the <p>
element as the user scrolls on the page.
Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down.
My Attempt
window.onscroll = function {scrHL};
function scrHL() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.querySelector('.main-p p').style.opacity = '1';
} else {
document.querySelector('.main-p p').style.opacity = '.3';
}
}
However, this code didn't achieve the desired effect. What am I missing?
How can I toggle the highlighting of <p>
each time a scroll event occurs?
Current Situation
https://i.sstatic.net/knLUh.gif
The current state is not producing the expected highlight when changing the numbers within the code. Why is that happening?
The Code
HTML
<div class="mai">
<section class="main-p"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></section>
</div>
CSS
.mai {
margin: 2.8rem 0 0 0;
height: 37.8rem;
overflow-y: scroll;
overflow-x: hidden;
-ms-overflow-style:none;
}
.mai::-webkit-scrollbar {
display:none;
}
.main-p {
white-space: pre-wrap;
}
JS
window.onscroll = function {scrHL};
function scrHL() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.querySelector('.main-p p').style.opacity = '1';
} else {
document.querySelector('.main-p p').style.opacity = '.3';
}
}