I did not find many ready examples of how to do this, so I decided to do it myself. See if that's what you want:
I created a div
with class="sideBar"
that you can have multiple articles, the "related", or anything else. I have represented this by several div.artigos
.
It looks like this:
<div class="sideBar" >
<div class="artigos"></div>
<div class="artigos"></div>
<div class="artigos"></div>
<div class="artigos"></div>
<div class="artigos"></div>
</div>
<div class="conteudo" >
</div>
Their respective styles:
.sideBar{
width: 180px;
height: auto;
float: right;
}
.conteudo{
width: auto;
height: 2000px;
background: #333;
margin-right: 200px;
}
.sideBar .artigos{
width: 100%;
height: 200px;
background: #f30;
margin-bottom: 5px;
}
I already did the code in JQuery:
$(document).scroll(function(){
var left = $('.sideBar').offset().left;
if($(this).scrollTop() >= $('.sideBar').height() - $('.artigos:last').height()){
$('.sideBar').css({
position: 'fixed',
top: -($('.sideBar').height() - $('.artigos:last').height()),
left: left
})
}else{
$('.sideBar').css({
position: 'relative',
top: 0,
left: '0'
})
}
})
I used the .scroll()
event of JQuery. When scrolling the page the first thing that will be done will be the capture of left
of .sideBar
. After that it will
check that the .scrollTop
of the document is greater than the size of the .sideBar
subtracted with the size of the last .artigos
, and if it is the div.sideBar
it will receive a position: fixed
, how it behaves considering the entire page , it will have a left
corresponding to the previous catch. The top
will be equal to the size of the .sideBar
subtracted with the size of the last .artigos
, but negative (even calculation of the scroll
check).
But if scroll
is less than the result of the calculation, div.sideBar
will receive position: relative
, and reset left
and top
.
Complete Code
Note that when a div.conteudo
finishes div.sideBar
is fixed, but if it comes back up, it runs again along with the rest.
$(document).scroll(function(){
var left = $('.sideBar').offset().left;
if($(this).scrollTop() >= $('.sideBar').height() - $('.artigos:last').height()){
$('.sideBar').css({
position: 'fixed',
top: -($('.sideBar').height() - $('.artigos:last').height()),
left: left
})
}else{
$('.sideBar').css({
position: 'relative',
top: 0,
left: '0'
})
}
})
.sideBar{
width: 180px;
height: auto;
float: right;
}
.conteudo{
height: 2000px;
background: #333;
margin-right: 200px;
}
.sideBar .artigos{
width: 100%;
height: 200px;
background: #f30;
margin:0 0 5px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="sideBar" >
<div class="artigos"></div>
<div class="artigos"></div>
<div class="artigos"></div>
<div class="artigos"></div>
<div class="artigos"></div>
</div>
<div class="conteudo" >
</div>
If you have trouble implementing your code, let me know.