(function() {
window.onscroll = function () {
var sideBars = document.getElementsByClassName("sideBar");
var y = window.pageYOffset;
var threshold = 200;
var marge = 15;
if(threshold - y >= marge) {
for(var i=0; i<sideBars.length; i++) { sideBars[i].style = "top: " + (threshold - y) + "px ;"; }
} else {
for(var i=0; i<sideBars.length; i++) { sideBars[i].style = "top: " + marge + "px ;"; }
}
};
})();
.sideBar { position: fixed; top: 200px; width: 300px; background-color: lightgreen; }
#sideBarLeft { left: 10px; }
<div id="sideBarLeft" class="sideBar">
<p>Quack.</p>
</div>
<div style="height: 1800px; background-color: yellow"></div>
I have created a simple JavaScript function to move an element while the user scrolls the page.
(function() {
window.onscroll = function () {
var sideBars = document.getElementsByClassName("sideBar");
var y = window.pageYOffset;
var threshold = 200;
var marge = 15;
if(threshold - y >= marge) {
for(var i=0; i<sideBars.length; i++) { sideBars[i].style = "top: " + (threshold - y) + "px ;"; }
} else {
for(var i=0; i<sideBars.length; i++) { sideBars[i].style = "top: " + marge + "px ;"; }
}
};
})();
It seems to work fine, but I have noticed that the browser gets slower as the user continues to scroll. I suspect there may be a memory leak or some other issue, but as I am not a JavaScript expert, I can't pinpoint the problem.
Can anyone provide some insights into this issue?
(tested on Mozilla Firefox 38.0.5)
The stackoverflow snippet does not seem to replicate the problem.
EDIT
Ahmed suggested using the translateY CSS function instead of resetting the "top" property. This change has improved the performance:
(function() {
window.onscroll = function () {
var sideBars = document.getElementsByClassName("sideBar");
var y = window.pageYOffset;
var origin = 200;
var marge = 15;
var offset = origin-y >= marge ? -y : marge-origin;
for(var i=0; i<sideBars.length; i++) { sideBars[i].style.transform = "translateY(" + offset + "px"; }
};
})();