Fade in on Scroll Down, Fade Out on Scroll Up - Based on Element Position in Window

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

$(window).on("load",function() {  $(window).scroll(function() {    var windowBottom = $(this).scrollTop() + $(this).innerHeight();    $(".fade").each(function() {      /* Check the location of each desired element */      var objectBottom = $(this).offset().top + $(this).outerHeight();            /* If the element is completely within bounds of the window, fade it in */      if (objectBottom < windowBottom) { //object comes into view (scrolling down)        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}      } else { //object goes out of view (scrolling up)        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}      }    });  }).scroll(); //invoke scroll-handler on page-load});
.fade {  margin: 50px;  padding: 50px;  background-color: lightgreen;  opacity: 1;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div> <div class="fade">Fade In 01</div> <div class="fade">Fade In 02</div> <div class="fade">Fade In 03</div> <div class="fade">Fade In 04</div> <div class="fade">Fade In 05</div> <div class="fade">Fade In 06</div> <div class="fade">Fade In 07</div> <div class="fade">Fade In 08</div> <div class="fade">Fade In 09</div> <div class="fade">Fade In 10</div></div>

Fade in and out when scroll up and down

Instead of using jQuery and scroll event listener, you can use the Intersection Observer API to achieve the desired result.

You can adjust the threshold option of the IntersectionObserver according to your needs. This option is used to indicate at what percentage of the target's visibility the observer's callback should be executed. I have set it to 70%.

const observerOptions = {
root: null,
rootMargin: "0px",
threshold: 0.7
};

function observerCallback(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// fade in observed elements that are in view
entry.target.classList.replace('fadeOut', 'fadeIn');
} else {
// fade out observed elements that are not in view
entry.target.classList.replace('fadeIn', 'fadeOut');
}
});
}

const observer = new IntersectionObserver(observerCallback, observerOptions);

const fadeElms = document.querySelectorAll('.fade');
fadeElms.forEach(el => observer.observe(el));
.fade {
margin: 50px;
padding: 50px;
background-color: lightgreen;
transition: opacity 0.7s ease-in;
}

.fadeOut { opacity: 0; }
.fadeIn { opacity: 1; }
<div class="container">
<div class="fade fadeOut">Element 1</div>
<div class="fade fadeOut">Element 2</div>
<div class="fade fadeOut">Element 3</div>
<div class="fade fadeOut">Element 4</div>
<div class="fade fadeOut">Element 5</div>
<div class="fade fadeOut">Element 6</div>
<div class="fade fadeOut">Element 7</div>
<div class="fade fadeOut">Element 8</div>
<div class="fade fadeOut">Element 9</div>
<div class="fade fadeOut">Element 10</div>
</div>

Cause arrow to fade out when scrolling down within div

It turns out I was loading jquery in the wrong spot (it was after this code rather than before). The code I was using worked:

$(document.getElementById('scrollsnap-container').scroll(function(){
$(".arrow").css("opacity", 1 - $(document.getElementById('scrollsnap-container')).scrollTop() / 250);
});

Importing jquery at the correct point resolved the issue.

How to fade in / fade out a button on scrolling down / up respectively

I've changed your code and removed setInterval usage. This can be solved with it but may be harder to understand for newer coders.

There are also flags to keep track of whether you are currently fading or unfading to ensure you do not stack or "overlap" timeout/intervals.

mybutton = document.getElementById("bottomtoup")

// initially, the button stays hidden
var visible = false

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};

function scrollFunction() {
var threshold = 20;
var below_threshold = document.body.scrollTop > threshold || document.documentElement.scrollTop > threshold;

if (below_threshold) {
if (!visible) { // if the button is not visible,
unfade(mybutton); // function to gradually fadein button
}

return;
}

if (visible) { // if the button is visible,
fade(mybutton); // function to gradually fadeout button
}
}

var current_opacity = 0.1;
var is_unfading = false;
var is_fading = false;

function unfade(element) {
if(!visible){
element.style.display = 'flex';
visible = true;
}

is_fading = false;
is_unfading = true;

unfade_step(element);
}

function unfade_step(element){
element.style.opacity = current_opacity;
element.style.filter = 'alpha(opacity=' + current_opacity * 100 + ")";

if (current_opacity >= 1){
// end
is_unfading = false;
current_opacity = 1;
return;
}

current_opacity += 0.01;
if(is_unfading){
setTimeout(function(){
unfade_step(element);
}, 10);
}
}

function fade(element) {
if(!visible){
return;
}

is_fading = true;
is_unfading = false;

fade_step(element);
}

function fade_step(element) {
element.style.opacity = current_opacity;
element.style.filter = 'alpha(opacity=' + current_opacity * 100 + ")";

if (current_opacity <= 0.001){
// end
is_fading = false;
visible = false;
current_opacity = 0.1;
element.style.display = 'none';
return;
}

current_opacity -= 0.01;
if(is_fading){
setTimeout(function(){
fade_step(element);
}, 10);
}
}

Fade in fade out images with scroll then scroll page content

I didn't see a possible solution to the problem by improving your code. This is a personal approach.

What I'm doing here, is changing the opacity of the element one inside the cover container as the user scrolls down the page, revealing the image below. After the opacity changes have been done, the script will change the filling container display style property from none to block. This element is just meant to fill the upper side of the cover container to prevent it from moving up when the position style property is changed from fixed to null.

And the reversed logic applies when scrolling back up.

const one = document.getElementById('one')
const cover = document.getElementById('cover')
const filling = document.getElementById('filling')

window.addEventListener('scroll', () => {
let scrollY = window.scrollY
let bottomHeight = window.innerHeight

if(scrollY / bottomHeight <= 1){
one.style.opacity = 1 - ( scrollY / bottomHeight )
cover.style.position = 'fixed'
filling.style.display = 'none'
}
else{
cover.style.position = null
filling.style.display = 'block'
}
})
*{padding:0;margin:0;border-size: border-box}

body{
height: 3500px;
}
img {
width: 100%;
height: 100vh;
}
#filling{
height:100vh;
width:100%
}
#cover{
height:100vh;
width:100%;
}
#cover > div{
height:100vh;
width:100%;
position:absolute;
}
#one{
z-index:2;
}
#two{
z-index:1;
}
<body>

<div id='filling' style='display:none'>
</div>

<div id='cover' style='position:fixed'>
<div id='one'>
<img src='https://picsum.photos/id/200/1000/1000'>
</div>

<div id='two'>
<img src='https://picsum.photos/id/201/1000/1000'>
</div>
</div>

<div>
<img src='https://picsum.photos/id/206/1000/1000'>
</div>

<div style='margin-top:-10px'>
<img src='https://picsum.photos/id/204/1000/1000'>
</div>

<div style='margin-top:-10px'>
<img src='https://picsum.photos/id/208/1000/1000'>
</div>

</body>

How do I make an element fade out on Scroll - my code worked elsewhere but not here

What you should do instead is run the function on window:

$(window).scroll(function(event) {
var scroll = $(window).scrollTop();
if (scroll > 110) {
$('.name-text').addClass('.my-name');
} else {
$('.name-text').removeClass('.my-name');
}
});

This way the code is reacting to the scroll listening for the change in position.



Related Topics



Leave a reply



Submit