0

I have 3 divs like <div class="diva">diva</div>,<div class="divb">divb</div>, and <div class="divb">diva</div>, with color red, yellow, and blue. All are cascaded one below other. They are 400 px wide and high.

I want to change color of div b and c to black when they approach the top of browser (on scrolling), say if they are 40px or below from top. How can I do this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Alfred
  • 21,058
  • 61
  • 167
  • 249
  • Releated: [How to tell if a DOM element is visible in the current viewport?](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) – Liam Jun 10 '14 at 10:05
  • I think you should check the offset of the divs with the window.top in window.srcoll() event – Think Different Jun 10 '14 at 10:05

3 Answers3

1

please try the following line of code:

jQuery(window).scroll(function(){
    if (jQuery(this).scrollTop() > 40 ) {
        $(".divb").css({
            "background":"black"
        })
        $(".divc").css({
            "background":"gray"
        })
}
});

40 is the value of your scroll pages taken from the distance from the top of your browser and when you malakukan Scrolling down and distance is more than 40 (40px), then jQuery will change the data in the css. Divb and. Divc. hopefully help

Road Name
  • 129
  • 14
0

solved using

$(window).scroll(function(){
  var xx = $(document).scrollTop();
  if(xx > 360){
    //change color
  }
})
Alfred
  • 21,058
  • 61
  • 167
  • 249
  • how does this do it for each div's? this will change the color for all three when the document has been scrolled 360 pixels.. it's not what you asked for.. – webkit Jun 10 '14 at 11:22
0

use jquery scrollTop() - ref

see it on jsfiddle


jquery:

$(window).scroll(function() {

    if($(window).scrollTop()>=828) {
        $("#divc").css({ "background":"black"} );
        $("#diva").css({ "background":"red"} );
        $("#divb").css({ "background":"green"} );
    }
    else if($(window).scrollTop()>=418) {
        $("#divb").css({ "background":"black"} );
        $("#diva").css({ "background":"red"} );
        $("#divc").css({ "background":"gray"} );
    }
    else if($(window).scrollTop()>8) {
        $("#diva").css({ "background":"black"} );
        $("#divb").css({ "background":"green"} );
        $("#divc").css({ "background":"gray"} );
    }
    else{
        $("#diva").css({ "background":"red"} );
    }
});

css:

body{
    padding:0px;
}
#diva,#divb,#divc{
    display:block;
    margin-bottom:10px;
    position:relative;
    width:400px;
    height:400px;
}
#diva{
    background:grey;
}
#divb{
    background:green;
}
#diva{
    background:red;
}

html:

<div id="diva"> diva </div>
<div id="divb"> divb </div>
<div id="divc"> divc </div>

<br/><br/><br/><br/><br/><br/><br/>
mostafaznv
  • 958
  • 14
  • 24