Reputation: 21396
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?
Upvotes: 0
Views: 227
Reputation: 988
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/>
Upvotes: 0
Reputation: 129
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
Upvotes: 1
Reputation: 21396
solved using
$(window).scroll(function(){
var xx = $(document).scrollTop();
if(xx > 360){
//change color
}
})
Upvotes: 0