Skip to content Skip to sidebar Skip to footer

Changing Background Color Of Div On Scroll

http://jsfiddle.net/ncuydr9y/ BG color should be #1A1A1A on start then change after scrolling 210 px. Not sure where I'm going wrong. $(document).ready(function(){ v

Solution 1:

You need to bind your scroll event to your div with id="left-panel", because that's the element that has the scrollbar on it (i.e. the element with overflow: auto and a child element larger than itself).

Binding to document or window won't work, because in this case they are not the element with the scrollbar.

Working Live Demo:

$(document).ready(function () {
    var scroll_pos = 0;
    $("#left-panel").scroll(function () {
        scroll_pos = $(this).scrollTop();
        if (scroll_pos > 210) {
            $("#left-panel").css('background-color', '#1A1A1A');
        } else {
            $("#left-panel").css('background-color', 'red');
        }
        console.log(scroll_pos);
    });
});
#left-panel {
    position: fixed;
    top: 0;
    left: 0;
    width: 80%;
    height: 100%;
    z-index: 2;
    overflow:auto;
    height:2000px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divid="left-panel"><divstyle="height:5000px;">CONTENT</div></div>

JSFiddle Version: http://jsfiddle.net/ncuydr9y/1/

Post a Comment for "Changing Background Color Of Div On Scroll"