12

I am facing a little problem here. I have basic knowledge about Javascript and i want to do the following:

Right now, when you scroll down, the menu will get smaller. when you go back up, it will return to normal. I call this event with window.onscroll:

var diff = 0;
function effects(){
var topDistance = (document.documentElement &&     document.documentElement.scrollTop) ||  document.body.scrollTop;
var clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

if(topDistance > diff){ 
    diff = topDistance;
    if(clientWidth > 1024){
        if(topDistance > 300){
            document.getElementById("header").style.marginTop= "-100px";
        }
    }
}else if(topDistance < diff){
    diff = topDistance;
    if(clientWidth > 1024){
        if(topDistance > 300){
            document.getElementById("header").style.marginTop= "0";
        }
    }
}
}

window.onscroll = effects();

Now i want another function to have some effects to my call to action buttons, lets call the function "test", but if i want to do this the same way like above, the effects functions does not work anymore:

function test(){
//do something
}
window.onscroll = test();

Any help is welcome! I tihnk it won't be a big challenge to do this, but i am doing it wrong i guess. (PS: NO JQUERY PLEASE)

Saypontigohe
  • 311
  • 1
  • 2
  • 15
  • So you want to call two functions on scroll? But do you also want to have `effects` style the header and `test` style some buttons but both do same scroll/offset height checks? – nem035 Oct 12 '16 at 12:33
  • 3
    As an aside,you might want to look at debouncing your onscroll function as well: https://davidwalsh.name/javascript-debounce-function – Alan Jenkins Oct 12 '16 at 12:39

3 Answers3

39

You override onscroll function by doing window.onscroll = blabla

You can do :

window.onscroll = function() {
  effects();
  test();
}

or

window.addEventListener('scroll', effects);
window.addEventListener('scroll', test);
Steeve Pitis
  • 4,283
  • 1
  • 21
  • 24
17

You can use multiple listener for the scroll event.

window.addEventListener('scroll', effects);
window.addEventListener('scroll', test);

That way you don't override window.onscroll

lukash
  • 668
  • 1
  • 5
  • 10
0

you should use

window.addEventListener

instead of window.onscroll

sfwnisme
  • 3
  • 3
  • Welcome to SO! Please take a look at the other answers that were given before. Your approach is mentioned there already. In order to keep the site clear and make it easy to find answers, we try to avoid double answers. – ahuemmer Dec 28 '22 at 11:52