Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when scrollbar reaches top of div?

I'm trying to animate a boxShadow on the scroll event of my #container div. Everything works except I can't figure out a good way to detect the scrollbar reaching the top so that the boxShadows can animate out. This is my code so far

   $('#container').scroll(
        function()
        {
            $('#white').animate(
            {
                boxShadow: "0 8px 8px -7px #696868"
            },
            "fast"); 
            if ($('#container').scrollTop() == 0)
            {
                $('#white').animate(
                {
                    boxShadow: "0 0 0 0 #696868"
                },
                "fast");
            }
        }
    );

I've added a demo. The initial on scroll animate works perfectly, but when the bar returns to top their is a rather long delay before the second animation kicks in. http://jsfiddle.net/JYqC3/14/

like image 646
Wilfred Avatar asked Apr 27 '12 03:04

Wilfred


People also ask

How do I know if my scroll is at the top?

scrollTop() – returns the current vertical position of the scroll bar. So if the scroll bar is at the very top, the value of $(window). scrollTop() will be Zero. Similarly if the value of the browser viewport + vertical position of scroll bar = document height, then the user has scrolled to the bottom of the page.

How do I get the scroll position of an element?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

What is $( window scrollTop ()?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .


1 Answers

Hope this helps

Used .scrollTop

$('#my_div').scroll(function() {
    var pos = $('#my_div').scrollTop();
    if (pos == 0) {
        alert('top of the div');
    }
});

DEMO

EDIT: better animation added to demo

like image 81
Dhiraj Avatar answered Oct 10 '22 09:10

Dhiraj