lupoll88 lupoll88 - 4 years ago 126
Javascript Question

JavaScript Conflict Parallax and Changing ID when Scrolling

I have Two Simple JavaScript Codes that help me do two things on my HTML document:

1) Number one creates a simple Parallax effect

2) And number two changes the ID of an HTML element when scrolling down

Each JavaScript code works great individually but not together.

Here is the parallax code:

(function(){

var parallax = document.querySelectorAll(".parallax"),
speed = 0.5;

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

var windowYOffset = window.pageYOffset,
elBackgrounPos = "0 " + (windowYOffset * speed) + "px";

el.style.backgroundPosition = elBackgrounPos;

});
};

})();


And here it is the changing ID code:

window.onscroll = function() {
console.log(window.pageYOffset);
var nav = document.getElementById('regMenu');
if ( window.pageYOffset > 100 ) {
nav.classList.add("fixMenu");
} else {
nav.classList.remove("fixMenu");
}
}


I already tried changing positions, like moving one down and moving the other one up but the one that stays at the top always win and the other one, the one below, stops working.

Can anyone help me to make both work?

Answer Source

You're not changing IDs. You're toggling classes. The former is a bad practice whereas the latter is pretty common.

Now, you see, if you define window.onscroll as a function in the global scope, and redeclare it somewhere, its behavior would become unpredictable. In this case, it seems the IIFE wins, I guess.

Anyway, you are expecting window.onscroll to behave like an event, to which you can suscribe two listeners. But this isn't the case, so the shorter path would be to declare just one function to perform both actions:

(function(){

  var parallax = document.querySelectorAll(".parallax"),
      speed = 0.5;

  window.onscroll = function(){
    var nav = document.getElementById('regMenu');
    if ( window.pageYOffset > 100 ) {
        nav.classList.add("fixMenu");
    } else {
        nav.classList.remove("fixMenu");
    }
    [].slice.call(parallax).forEach(function(el,i){

      var windowYOffset = window.pageYOffset,
          elBackgrounPos = "0 " + (windowYOffset * speed) + "px";

      el.style.backgroundPosition = elBackgrounPos;

    });
  };

})();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download