How to stop onscroll event error if you use it for a shared element in all pges and a single element in one page only

91 Views Asked by At

The problem is:

background is only in the first page but div is shared in all pages.

without inspection, it all looks fine.

but when I inspect on browsers on the other pages that don't have background, I get the following error with every single scroll.

Uncaught TypeError: background is null
    scroll http://100.0.0.0:0000/script.js:83
    EventListener.handleEvent* http://100.0.0.0:0000/script.js:78
191 script.js:83:5
    scroll http://100.0.0.0:0000/script.js:83
    (Async: EventListener.handleEvent)
    <anonymous> http://100.0.0.0:0000/script.js:78

I solved the problem by creating a separate js file that only includes the scroll code for home page. it worked fine but I was wondering if I could solve it without creating a new js file.

// show the div and change background opacity on scroll
    
    let background= document.getElementById("background");
    let div= document.getElementById("div");
    
    window.addEventListener("scroll", scroll); 
    
    function scroll() {
      if (window.scrollY >= 500) {
        div.style.display= "block"
        background.style.opacity = "0.05";
      } else {
        div.style.display= "block"
        background.style.opacity = "0.3";
      }
      
    }
1

There are 1 best solutions below

1
krzszk On

You could use if statement to check on what page you are, and use it only on desired page.

function scroll() {
      if (window.scrollY >= 500) {
        div.style.display= "block"
        if ( document.URL.includes("homepage.html") ) {
          background.style.opacity = "0.05";
        }            
      } else {
        div.style.display= "block"
        if ( document.URL.includes("homepage.html") ) {
          background.style.opacity = "0.3";
         }            
      }          
    }