JavaScript add CSS to style won't work?

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 : )

I am simply using 2 divs that have IDs mentioned in the JavaScript 1 and 2

<div id="socials2">Share buttons</div>

<div id="floating_share_buttons"> Share buttons</div>

Please could you combine them I would really appreciate your help.

Lol. Then post enough code that I can recreate your problem :slight_smile:
A link to a demo page is also fine.

I am working on the local host for the second code! But you can see the first JavaScript in action here: http://letsforum.com/Forum-Search-Engine-Optimization

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?

such as replacing both event handlers with event listeners so that they can both be triggered by the scroll instead of one overwriting the other.

Please would you be so nice to combine the code I am not really into JavaScript please?

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.

1 Like

I’d use two separate scroll listeners to make it easier to use one of the scripts on a page without the other.

How do you mean?

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).

Presumably there is a reason the two scripts were separate in the first place.

Of course if they are ALWAYS to be used together then there is no reason not to combine the code as you have done.

1 Like

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.

OMG this is perfect.

How can a make this code to add some other css styles since it only adds top:10;

I would like to add this css to socials2

element.style {    left: 8px;    top: 12px;    width: 50%;    z-index: 10;}

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.

Do you means some like this:

if(pageYOffset > el.dataset.position){
      el.classList.add("class");
      el.style.top = elTop;
    } else {
      el.classList.remove("class");
      el.style.top = "";
    }
  };

I think it will be applied to both share buttons I only want the left one!

Could you help please?

I mean more like this (untested):

<style>
  .el1{ ... }
  .el2{ ... }
</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, className){
    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(className);
    } else {
      el.classList.remove(className);
    }
  };

  window.addEventListener("scroll", function(){
    stickElement('floating_share_buttons', "el1");
    stickElement('socials2', "el2");
  });
1 Like

This is finally it OMG +1 and +1000 thanks. Really thank you very much you rock!

No problems : )

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.