Home > Blockchain >  Combining two similiar .js functions to one
Combining two similiar .js functions to one

Time:04-21

I know this is basic for most of you but im not that experienced on this language. So when i add both of the codes to functions.php they dont work. But it only works when i use only one of them. So im thinking maybe it would work if they both were in the same code lines. I tried to do that but couldnt make it work.

This is the first function

window.onscroll = function() {
    scrollFunction()
};
    
function scrollFunction() {
    if (document.body.scrollTop > 90 ||
        document.documentElement.scrollTop > 90)
    {
        document.getElementById("quadmenu_0")
                    .style.padding = "20px 0px";

    }
    else {
        document.getElementById("quadmenu_0")
                    .style.padding = "180px 0px 40px";
            
    }
}

And this is the second function

window.onscroll = function() {
    scrollFunction()
};
    
function scrollFunction() {
    if (document.body.scrollTop > 150 ||
        document.documentElement.scrollTop > 150)
    {
        document.getElementById("ast-mobile-header")
                    .style.backgroundColor = "red";

    }
    else {
        document.getElementById("ast-mobile-header")
                    .style.backgroundColor = "white";
            
    }
}

CodePudding user response:

You can call both functions within the onScroll listener. They will need to of course have different names (and best to choose something more logical than the below example)

window.onscroll = function() {
    scrollFunction1()
    scrollFunction2()
};
function scrollFunction1() {
  if (document.body.scrollTop > 90 ||
    document.documentElement.scrollTop > 90) {
      document.getElementById("quadmenu_0")
        .style.padding = "20px 0px";
  } else {
    document.getElementById("quadmenu_0")
      .style.padding = "180px 0px 40px";      
  }
}
function scrollFunction2() {
  if (document.body.scrollTop > 150 ||
    document.documentElement.scrollTop > 150) {
      document.getElementById("ast-mobile-header")
        .style.backgroundColor = "red";
  } else {
    document.getElementById("ast-mobile-header")
      .style.backgroundColor = "white";
  }
}
  • Related