One onscroll handler is overwriting the other.
You should just be able to combine them, or alternatively, if you can provide enough code to reproduce your problem, we can probably find a more elegant solution : )
This #1 Java is controlling “Please share and like us.” buttons on the right!
I would like the #2 Java to do the same to the “Sharing is caring!” share buttons on the left!
The second code is not yet implemented on the site would you please help?
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.
Then, we can alter the stickElement function to remove any reliance on global variables, storing any necessary properties on the element itself. Full code:
The original code has two separate scripts. I’d keep the scripts separate to allow them to be used separately.
In each of the two scripts I’d replace the window.onscroll=function() with window.addEventListener("scroll", function(){ so that both scripts add their own scroll listener to the window.
Then you don’t have the two scripts linked together and can use either or both on a page.
Really? That’d mean quite a bit of duplication. Is there a downside to making it more generic?
I guess ideally, you would just want to apply a class of sticky to any elements you want stuck and have some JS work out where to position what (but there are plenty of plugins that do that already).
Ah right, you mean that if the first element is not there for some reason, the second will stick in the wrong place. Lol, I guess I’m too tired. That could probably be sorted out, but I’ll wait for the OP to return and see what they say.
Well, you could change the stickElement function so that the second parameter is a class name to be applied. Then you could stzle each element as you wish.