-2

Ive seen a number of solutions that let you use scrolltop (which means you have to measure where the scroll is).

Im wondering if it is possible to fade in/out a div, when it hits the screen or gets to the top of the screen/viewport?

Cheers

Ke

Ke.
  • 2,484
  • 8
  • 40
  • 78
  • What do you mean by "hits the screen"? – FrEaKmAn Aug 30 '14 at 18:17
  • When youre scrolling downwards, when the div becomes visible in the viewport – Ke. Aug 30 '14 at 18:18
  • then check http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom – FrEaKmAn Aug 30 '14 at 18:19
  • ok that tells me how to determine when a div hits the viewport, but not how to fade in/out – Ke. Aug 30 '14 at 18:21
  • are you using any libraries? you can simply use jQuery and http://api.jquery.com/fadein/ and http://api.jquery.com/fadeout/. How to use them in described in the examples. – FrEaKmAn Aug 30 '14 at 18:22
  • Yes, I'm aware of all of this. What I am not clear on is how to activate fade when the div appears on the screen (from scrolling). I cannot use scrolltop, because my page is very long. I want to detect when the div appears in the viewport and then fade in based on that. – Ke. Aug 30 '14 at 18:31

2 Answers2

0

Using JQuery: Detect bottom:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
       $("#divId").FadeIn("400")
   }
});

Detect top:

$(window).scroll(function() {
   if($(window).scrollTop()  == 0) {
       alert("top!"); 
      $("#divId").FadeOut("400");
   }
});

Hope it Helps

Khaleel
  • 1,212
  • 2
  • 16
  • 34
  • Hi Khaleel, this doesn't do what im looking for. It alerts "top" when you scroll to the top of the page. Im trying to determine when youre scrolling at the top of the div (which is a long way down the page) – Ke. Aug 30 '14 at 18:29
  • Oh yeah.. let me come up with tat – Khaleel Aug 30 '14 at 18:31
0

Based on How to tell if a DOM element is visible in the current viewport?. The code is untested, hopefully you understand it. Basically check if element is visible in the viewport, and if yes fadeIn or if no then fadeOut.

function isElementInViewport(el) 
{
    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= $(window).height() &&
        rect.right <= $(window).width()
    );
}

var $element = $('#element');
$(window).on('DOMContentLoaded load resize scroll', function()
{
    if(isElementInViewport($element[0]))
    {
        // we check if fadeIn is in progress
        if(!$element.is(":visible"))
        {
            $element.fadeIn();
        }
    }
    else
    {
        $element.fadeOut();
    }
}); 
Community
  • 1
  • 1
FrEaKmAn
  • 1,785
  • 1
  • 21
  • 47