I have an element with position:fixed, bottom:0px. As I scroll down the page this element is supposed to follow me until it gets closer to the footer, lets say 100px height, I am trying to allow the element stay at bottom:0px until it reaches the footer element, in that moment it should always let the footer element be below it.
This is my css:
#backToTop{
width:80px;
height:50px;
background:#333;
color:#FFF;
text-align:center;
border-radius:10px 10px 0 0;
padding-top:10px;
position:fixed;
bottom:0;
left:50%;
margin-left:550px;
}
I have looked into Jquery's $(document).height()
and $(window).scrollTop()
to try to come up with some kind of conditional that will detect when the position of the element is close to the footer, but no success (the height of my footer is 120):
$(window).scroll(function(){
if($(document).height()-($(window).scrollTop()+$(window).height()) <= 120){
$('#backToTop').css({'bottom':$(document).height()-($(window).scrollTop()+$(window).height())});
}else{
$('#backToTop').css('bottom',0);
}
});
I am not quite sure where exactly those values are pointing to, any hints? Thanks.
Try creating two classes for the #backToTop element, one for fixed and another for relative position. When footer reaches the viewport, #backToTop element changes its class to 'relative'.
HTML:
<div id="container">
<div id="backToTop" class="fixed_pos">Top</div>
<footer>footer</footer>
</div>
CSS:
#container {
width: 100%;
height: 1000px;
float: left;
}
#backToTop {
width:80px;
height:50px;
background:#333;
color:#FFF;
text-align:center;
border-radius:10px 10px 0 0;
padding-top:10px;
left: 50%;
margin-left: -40px;
}
.fixed_pos {
position:fixed;
bottom:0;
}
.relative_pos {
position: relative;
top: 100%;
}
footer {
width: 100%;
height: 200px;
float: left;
position: relative;
top: 100%;
background: #333;
color: #fff;
text-align: center;
}
Have a look here: