Archived topic
Fade in/out according to scrolling down/up
7 replies · Started by Kai on December 27, 2020
I have been searching around and do some trial-and-error, but no luck. I am looking for something like the second answer in this post: https://stackoverflow.com/questions/26694385/fade-in-on-scroll-down-fade-out-on-scroll-up-based-on-element-position-in-win
My site is nguyen-kai.com - as you can see, it is pretty basic.
Hi,
How are you adding the script?
You can use Hook element to place your script.
https://docs.generatepress.com/article/hooks-element-overview/
You can copy the known working script and place it within the Hook element's code area wrapped within a <script>...</script>
You then hook it to wp_footer.
I see. So what I did was the following but it did not work out:
1. Go to Dashboard >> Appearance >> Elements >> "Add New Element".
2. When prompted to choose the element type, I choose "Hook".
3. In the code section, I added:
<script>
$(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
});
</script>
4. I open my website, nguyen-kai.com, then open Additional CSS, and pasted this:
.fade {
margin: 50px;
padding: 50px;
background-color: lightgreen;
opacity: 1;
}
Hi,
You're site has a error. This line is causing it:
if (objectBottom < windowBottom)
Fix < and place <.
Also, you're referencing .fade class from $(".fade") but there seems to be no element using it so the animation is not applying on anything.
You can try adding fade class on your GenerateBlocks Container Blocks through its advanced settings.
Ah wow I did not even notice both of those! Thank you. Unfortunately, I think that since I use jQuery, it is not compatible with Wordpress or at least my site somehow. As I am on my site, I am seeing an error saying that "$ is not a function".
As I am on my site, I am seeing an error saying that “$ is not a function”.
Ah right of course. My bad. I forgot to mention that you'll have to change all of the $ to jQuery.
Or keep it but make sure you use .noConflict(). (this may be confusing, using jQuery instead of $ should work.)
https://api.jquery.com/jquery.noconflict/
Reminder: I still don't see the use of fade class in any of your elements. This script won't do anything unless there's an element with fade class within your page.
Thank you so much!
No problem. :)