Ori
Ori

Reputation: 259

How to make a div stick near the top of the page on scroll?

How can I get the two purple buttons on this page (or rather the white parent container slide2) to stick right underneath the red header div when it hits the bottom edge of it upon scrolling?

I created this fiddle: http://jsfiddle.net/baumdexterous/K7NSX/

A similar example of what I'm trying to accomplish: http://jsbin.com/ijexe

HTML:

<div id="container">

    <div class="menu">
        <div class="container clearfix">

            <div id="header" class="grid_12">
            </div>
        </div>
    </div>


    <div class="slide" id="slide1">
        <div class="container clearfix">

            <div id="section1" class="grid_12">
            </div>


        </div>
    </div>

    <div class="slide" id="slide2">
        <div class="container clearfix">

            <div id="test" class="grid_6">
                <a href="" target="_blank" class="btn1"></a>
            </div>

            <div id="test" class="grid_6 omega">
                <a href="" target="_blank" class="btn2"></a>
            </div>

        </div>
    </div>

    <div class="slide" id="slide3">
        <div class="container clearfix">

            <div id="section3" class="grid_12">
            </div>
        </div>
</div>

Thanks so much!

Upvotes: 1

Views: 4131

Answers (2)

Real Liu
Real Liu

Reputation: 36

Check this out...... it's what you want.

http://www.jsfiddle.net/5ADzD/1

$window.scroll(function(event) {
   var scrollTop = $window.scrollTop()
   if (scrollTop >  ... )
   {
       //execute code
   }
   else
   {
       //execute other code
   } 
});

Upvotes: 2

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

Try this script.

 var $window = $(window);
            $stickyEl = $('#youelementID');
            var elTop = $stickyEl.offset().top;
            $window.scroll(function() {
                var windowTop = $window.scrollTop();
                $stickyEl.toggleClass('sticky', windowTop > elTop);
            });

/// and Css

.sticky
{
    position: fixed;
    top: 0px;
}

Upvotes: 0

Related Questions