Sure.
The first thing I would alter is that the element’s style properties are set in the JavaScript (e.g. bar.style.position='relative';
). Instead I would apply a class when the element scrolls off the top of the screen and remove it when it scrolls back into view:
<style>
.stuck{
position: fixed;
top: 15px;
right:0;
width:100%;
background:#f9f9f9;
border-bottom:1px solid #cecece;
padding:5px 10px 10px;
}
</style>
<script type='text/javascript'>
var startProductBarPos=-1;
function findPosY(obj) {
var curtop = 0;
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}
window.onscroll=function(){
var bar = document.getElementById('floating_share_buttons');
if(startProductBarPos<0){
startProductBarPos=findPosY(bar);
}
if(pageYOffset>startProductBarPos){
bar.classList.add("stuck");
} else {
bar.classList.remove("stuck");
}
};
</script>
Then as felgal says, we can put everyting into an event listener, from within which you can call the stickElement
function, passing it the element to stick and a value from the top to stick it.
window.addEventListener("scroll", function(){
stickElement('floating_share_buttons', "15px");
stickElement('socials2', "52px");
});
Then, we can alter the stickElement function to remove any reliance on global variables, storing any necessary properties on the element itself. Full code:
<style>
.stuck{
position: fixed;
right:0;
width:100%;
background:#f9f9f9;
border-bottom:1px solid #cecece;
padding:5px 10px 10px;
}
</style>
<script type='text/javascript'>
function findPosY(obj) {
var curtop = 0;
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}
function stickElement(id, elTop){
el = document.getElementById(id);
if(el.dataset.initialized !== "true"){
el.dataset.position = findPosY(el);
el.dataset.initialized = "true";
}
if(pageYOffset > el.dataset.position){
el.classList.add("stuck");
el.style.top = elTop;
} else {
el.classList.remove("stuck");
el.style.top = "";
}
};
window.addEventListener("scroll", function(){
stickElement('floating_share_buttons', "15px");
stickElement('socials2', "52px");
});
</script>
Here’s a demo of it working as expected.