简体   繁体   中英

Fixed side bar on scroll

I am trying to add a script to my page to fix my side bar when the user has reached the bottom of it.

I have tried to add a class to the container of my side bar to fix its position by implementing the script and the CSS below:

Script

 function fixeSideBar() {
    var myWindow = $( window ),
        mySideBar = $( ".widget-area" );

    myWindow.scroll ( function() {
            if ( myWindow.scrollTop() < 130 ) {
            mySideBar.removeClass( "sticks" );
        } else {
            mySideBar.addClass( "sticks");
        }
    } );
}

$(function() {
        fixeSideBar();
    } ); 

CSS

.sticks { position: fixed; top:-50px; float:right; left:1000px; padding-top:62px; width:37%; background-color: #fafafa; padding-right: 40px; padding-left:40px; }

However, I am facing two main issues:

  1. By adding this new class, I lose the entire formatting of my side bar (which includes its position on the right side of the screen).

  2. The entire formatting works fine only on my computer (with a specific screen width and height).

What I would like to accomplish ultimately will be to fix the side bar when the user reaches its bottom (on any type of device), and make sure that the formatting of my side bar stays the same.

try this

myWindow.scroll ( function() {
        if ( myWindow.scrollTop() <= mySideBar.offset().top +mySideBar.height() ) {
        mySideBar.removeClass( "sticks" );
    } else {
        mySideBar.addClass( "sticks");
    }
} );

If you want that sidebar to be fixed when bottom of that div is reached you add meSideBar.height() in condition and if you want sidebar to be fixed just as div is shown remove it

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