Fade In a div when it scrolls to the viewport

Ok, so I was looking for an easy way to disappear into the div when the user is viewing it, but I cannot find a direct solution.

HTML

<div class="container"> <div class="topdiv">This is a 100% height div. User scrolls down from here.</div> <div class="fadethisdiv">This content should be faded in once .fadethisdiv is [so many]px into the bottom of the viewport. Let use 150px as an example.</div> </div> 


CSS

 .container { width:100%; height:600px; } .topdiv { height:100%; background-color:#09f; text-align:center; font-size:24px; } .fadethisdiv { height:100%; background-color:#36afff; text-align:center; font-size:24px; } 


Js

 // Talk to me. 

Here's the script: http://jsfiddle.net/kz2z5/2/

+8
jquery html opacity scroll fadein
source share
3 answers

Here's a solution that runs the fadeIn jQuery function after scrolling .topdiv div .topdiv .

It subtracts the viewport size from the scrollTop function to get the bottom of the scroll position, and then checks to see if its value exceeds the height of the .topdiv div plus 150 pixels or, oddly enough, how to do it fadeIn at.

Since the div must first be displayed on the page so that we scroll down somewhere, we set visibility to hidden instead of using display:none . We use fadeIn , which expects the element to start with display:none , so we .fadethisdiv div .fadethisdiv and fade it out.

Then we remove the scroll listener so that the element does not hide hidden text and fadeIn after scrolling .fadethisdiv scroll.

 $(window).scroll(function () { console.log($(window).scrollTop()); var topDivHeight = $(".topdiv").height(); var viewPortSize = $(window).height(); var triggerAt = 150; var triggerHeight = (topDivHeight - viewPortSize) + triggerAt; if ($(window).scrollTop() >= triggerHeight) { $('.fadethisdiv').css('visibility', 'visible').hide().fadeIn(); $(this).off('scroll'); } }); 

Fiddle

+9
source share

I found the AOS library very useful for this purpose ( https://github.com/michalsnik/aos#-animations ). In addition, to fade when your div enters the viewport, other effects are available. Example below

 <script src="js/aos.js"></script> <link href="css/aos.css" rel="stylesheet" /> <div id="content1" data-aos="flip-down" data-aos-delay="0"> <p>Some content</p> </div> <script type="text/javascript"> $(document).ready(function () { AOS.init(); AOS.refreshHard(); //optional }); </script> 
+2
source share

Here is the solution set to 300px

 $(document).ready(function(){ var view = {}; var checkPosition = function(){ var elem = $('.fadethisdiv'), top = elem.offset().top; if (top - view.limit < 300) { elem.css('display','none'); } }; $(window).bind('scroll', function() { view.top = $(window).scrollTop(); view.limit = view.top + $(window).height(); checkPosition(); }); }); 

http://jsfiddle.net/kz2z5/4/

Enjoy! :)

0
source share

All Articles