0

I'm using two functions to shift the background position and to zoom div's background. Here they are:

(function(shifting) {

    var parallax = document.querySelectorAll(".shiftparallax"),
        speed = -0.05;

    window.onscroll = function() {
        [].slice.call(parallax).forEach(function(el, i) {

            var windowXOffset = window.pageYOffset,
                elBackgrounPos = (windowXOffset * speed) + "px";
            console.log(elBackgrounPos);
            el.style.backgroundPositionY = elBackgrounPos;

        });
    };

})();


(function(zooming) {
    var parallaxfacts = document.querySelectorAll(".parallaxfacts"),
        constantsize = 100;
    speed = -0.03;
    window.onscroll = function() {

        if (window.innerWidth > 1024) {
            [].slice.call(parallaxfacts).forEach(function(el, i) {

                var windowXOffset = window.pageYOffset,
                    elBackgrounScale = (windowXOffset / 950 * constantsize) + "%";

                el.style.backgroundSize = elBackgrounScale;

            });
        }
    };

})();

The problem is that I need them both to run at the same time but they only run separately. If they are both written like that - the second one runs only and the first one does nothing. If I remove the second one, the first one starts working. I've got a bit rusty in JS lately so I can't figure it out. is there any way to make them both work?

Nebular Dust
  • 403
  • 1
  • 6
  • 17

2 Answers2

1

You overwrite the window.onscroll event

try this two lines:

window.onscroll = el => console.log ('first');
window.onscroll = el => console.log ('second');

use the following code...

window.addEventListener('scroll',  el => console.log ('firstlistener'));
window.addEventListener('scroll',  el => console.log ('secondlistener'));
Frank Wisniewski
  • 1,182
  • 8
  • 7
1

You're assigning to window.onscroll twice. That means the second handler "unregisters" the first.

You can use addEventListener to listen to the event in both functions:

window.addEventListener("scroll", function() { /* function 1*/ });
window.addEventListener("scroll", function() { /* function 2*/ });
joews
  • 29,767
  • 10
  • 79
  • 91