Erik
Erik

Reputation: 45

Sticky Sidebar - Stop at element?

I want to have a stick sitebar. I searched and found this code:

<script>
    var sidebar = $('#sidebar-content'),
        nav = $('.sidebar-content'),
        startPosition = sidebar .offset().top,
        stopPosition = $('#abspann').offset().top - nav.outerHeight();

    $(document).scroll(function () {
        //stick nav to top of page 
        var y = $(this).scrollTop()

        if (y > startPosition) {
            nav.addClass('sticky');
            if (y > stopPosition) {
                nav.css('top', stopPosition - y);
            } else {
                nav.css('top', 0);
            }
        } else {
            nav.removeClass('sticky');
        } 
    });
</script>

The problem is that it doesn't work... I already tried to replaced the $ with a jQuery but still... doesn't work. The only reason can be the error I still get in the console:

Uncaught TypeError: Cannot read property 'top' of undefinedat (index):411

Currently the code is looking like this:

<script>
var sidebar = jQuery('#sidebar-wrap'),
    nav = jQuery('.sidebar-content'),
    startPosition = jQuery('#sidebar-wrap').offset().top,
    stopPosition = jQuery('#abspann').offset().top - nav.outerHeight();

jQuery(document).scroll(function () {
    //stick nav to top of page
    var y = jQuery(this).scrollTop()

    if (y > startPosition) {
        nav.addClass('sticky');
        if (y > stopPosition) {
            nav.css('top', stopPosition - y);
        } else {
            nav.css('top', 0);
        }
    } else {
        nav.removeClass('sticky');
    } 
});
</script>

If it's working, the sidebar should stop at the element #abspann. Just to know.

The site I'am talking about is this. And the sourcecode can be found here.

How can I get this working?

Kind Regards

Upvotes: 1

Views: 489

Answers (1)

Rohan Kumar
Rohan Kumar

Reputation: 40639

It is because your script is loaded before loading your elements so use $.ready() so that every element is available before using it.

<script src="JQUERY_LIB_URL_HERE"></script>
<script>
    jQuery(function(){
       var sidebar = jQuery('#sidebar-wrap'),
        nav = jQuery('.sidebar-content'),
        startPosition = jQuery('#sidebar-wrap').offset().top,
        stopPosition = jQuery('#abspann').offset().top - nav.outerHeight();
        jQuery(document).scroll(function () {
            //stick nav to top of page
            var y = jQuery(this).scrollTop()

            if (y > startPosition) {
                nav.addClass('sticky');
                if (y > stopPosition) {
                    nav.css('top', stopPosition - y);
                } else {
                    nav.css('top', 0);
                }
            } else {
                nav.removeClass('sticky');
            } 
        });
    });
</script>

Upvotes: 1

Related Questions