Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change CSS when user scrolls past a certain div

I'm trying to implement a scroll function which moves elements based on where the user scrolls, this code works so far and it does move elements.

The thing is I want to have a list of different functions which moves specific elements whenever you scroll past a certain div based on it's id or class.

I thought if I changed $("#pagelight2").scrollTop() it would work but that did not help

Any guidance would be appreciated

Thanks

Updated code works but it is really glitchy whenever I scroll up the animation stops moving - anybody know more efficient way to get this to work?

    var $scrollingDiv = $(".Page3-PeopleWalkingDown");

    var p = $("#pagedark3");

    var offset = p.offset();

    var top = offset.top;

    $(window).scroll(function() {

                var scrollval = $(window).scrollTop() - top;

                if ($(window).scrollTop() > 1400) {
                    $scrollingDiv
                        .stop()
                        .animate({
                            "left": "-" + (scrollval) + "px"
                        });

                } else


                {

                    $scrollingDiv
                        .stop()
                        .animate({
                            "left": +(0) + "px"
                        });
                }
like image 448
Hashey100 Avatar asked Nov 28 '22 07:11

Hashey100


2 Answers

Skrollr allows you to animate any CSS property of any element (if you know the position/offset of your div) depending on the scrollbar position.

For example, you can change the background-color of a div starting at red when the scrollbar is at the top and ending with green when the top of div hits the top of the window.

var s = skrollr.init();
<script src="http://prinzhorn.github.io/skrollr/dist/skrollr.min.js"></script>

<div style="height: 100px"></div>
<div data-0p="background-color: red;" data-100="background-color: !green;" style="height: 200px;background-color: red;" >
</div>
like image 42
Pier-Alexandre Bouchard Avatar answered Nov 30 '22 21:11

Pier-Alexandre Bouchard


What you need to do is calculate the offset height of each specific DIV with respect to the top of the page or scrollable area.

Then, using your .scroll() function, when the offset is reached (i.e. the 'div' offset matches the 'scroll' position) you can fire your animation off.

Also, (based on a slightly different offset (e.g. div offset -600px) you could 'reset' the animation if the user scrolls back up the page, past the animation. Although, this might end being annoying to the user and more work than benefit . . .

offset : http://api.jquery.com/offset/

scrollTop : http://api.jquery.com/scrolltop/

like image 97
Pat Dobson Avatar answered Nov 30 '22 20:11

Pat Dobson