简体   繁体   中英

How to fix a sidebar on scroll?

I am using this javaScript function to make a the right-side bar fixed:

<script type="text/javascript">
$(document).ready(function () {  
    var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsidebar-wrapper').css('marginTop').replace(/auto/, 0));
    $(window).scroll(function (event) {
        // what the y position of the scroll is
        var y = $(this).scrollTop();
        // whether that's below the form
        if (y >= top) {
           // if so, ad the fixed class
           $('#rightsidebar-wrapper').addClass('fixed');
        } else {
            // otherwise remove it
            $('#rightsidebar-wrapper').removeClass('fixed');
        }
    });
}); 
</script>

And this CSS to style the rightsidebar div:

#rightsidebar-wrapper {
    background: #ffffff;
    width: 225px;
    float: right;
    margin-top: 8px 0px 0 0;
    padding:0px;
    word-wrap: break-word;
    overflow: hidden;
}

#rightsidebar-wrapper.fixed {
    position: fixed;
    top: 5px;

}

This is a sidebar placed at right. The problem is that When the sidebar top meets the top-end of the screen on scrolling, it get floats to the left . On adding this to the CSS

right: 10%;

it fixes the problem but when the page is Zoomed-in or Zoomed-out it again looses its position. Any idea how to fix this?

I know this post is way too old but i hope someone in the future looking for this answer WITHOUT Bootstrap may find it useful. It works for a responsive site too.

For first, create a div with the following css properties.

#scroll_to{
    padding: 25px;
    display: inline-block;
    float: right;
    background-color: #eeeeee;
}

It will create a floating box on the right side of the window.

Then apply this JS code to your div and it'll work.

Note: Please set the top: value according to your header bar

var div_pos= $('#scroll_to').position().top;
$(document).on('scroll', function() {
    var scroll_top= $(this).scrollTop();
    if(scroll_top>=div_pos){
        console.log("fix");
        $('#scroll_to').css({
            'position': 'fixed',
            'right': '0',
            'top': '36px'
        });

    }else{
        $('#scroll_to').css({
            'position': '',
            'right': '',
            'top': '36px'
        });
    }
});

That's because position: fixed is excreted with float. Pobably you have to set position absolutely by JavaScript. You can use $(window).resize() to fix the zoom-in/zoom-out problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM