Carlos, the first thing to do is to delimit an area for your columns, you can use an element that wraps the left and right columns,
Then add a listener to the scroll event for this container, this way you will be able to anchor the right column at the top or bottom of this container.
follows an implementation suggestion:
var container = document.querySelector(".container");
var content = document.querySelector(".content");
var esquerda = document.querySelector(".esquerda");
var alturas = document.querySelectorAll(".altura");
var margin = {};
var style = window.getComputedStyle(esquerda, null);
margin.Top = parseInt(style.getPropertyValue("margin-top").replace("px", ""));
margin.Bottom = parseInt(style.getPropertyValue("margin-bottom").replace("px", ""));
margin.Total = margin.Top + margin.Bottom;
var prevTop = container.scrollTop;
container.addEventListener("scroll", function (event) {
if (esquerda.offsetHeight > container.offsetHeight) {
if (prevTop < container.scrollTop) {
var pos = container.scrollTop + container.offsetHeight;
var esq = esquerda.offsetHeight + esquerda.offsetTop;
if (pos > esq) {
esquerda.style.top = (pos - esquerda.offsetHeight - margin.Total) + "px";
}
} else if (container.scrollTop < esquerda.offsetTop) {
esquerda.style.top = container.scrollTop + "px";
}
} else {
esquerda.style.top = container.scrollTop + "px";
}
prevTop = container.scrollTop;
});
[].forEach.call(alturas, function (altura, indice) {
altura.addEventListener("input", function (event) {
event.target.parentNode.parentNode.style.height = altura.value + "px";
var event = new Event("scroll");
container.dispatchEvent(event);
});
});
html, body {
position: relative;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
.header {
position: absolute;
background-color: whitesmoke;
top: 0px;
height: 40px;
width: 100%;
box-shadow: 0px 0px 10px black;
z-index: 2;
}
.container {
position: absolute;
background-color: white;
top: 40px;
bottom: 80px;
width: 100%;
overflow: auto;
z-index: 1;
}
.footer {
position: absolute;
background-color: whitesmoke;
bottom: 0px;
height: 80px;
width: 100%;
box-shadow: 0px 0px 10px black;
z-index: 2;
}
.content {
width: 100%;
min-height: 100%;
}
.esquerda {
position: absolute;
background-color: whitesmoke;
box-shadow: 0px 0px 10px black;
width: 300px;
height: 1800px;
margin: 10px;
border-radius: 5px;
left: 0px;
top: 0px;
}
.direita {
position: absolute;
background-color: whitesmoke;
box-shadow: 0px 0px 10px black;
height: 2800px;
margin: 10px;
border-radius: 5px;
left: 320px;
right: 0px;
top: 0px;
}
#altura {
margin: 5px;
}
<div class="header">
</div>
<div class="container">
<div class="esquerda">
<label>
Altura desta div
<input class="altura" type="number" value="1800" step="100" min="100" max="5000" />
px
</label>
</div>
<div class="direita">
<label>
Altura desta div
<input class="altura" type="number" value="2800" step="100" min="100" max="5000" />
px
</label>
</div>
</div>
<div class="footer">
</div>