Search code examples
javascriptfunctionscrolladdeventlistener

How to fire window.scrollY only one time


I am trying to fire window.scrollY only one time, currently my below code works fine but fire multiple times.

When i run this code it fired multiple times i want to stop this, only window scroll should fire only one time when we scroll the browser.

window.addEventListener("scroll", function() {
    window.scrollY > 30 && fetch("https://ip2c.org/self").then((function(t) {
        t.text().then((function(t) {
            t.includes("IND") && (document.getElementById("IN").style.display = "flex")
        }))
    }))
});

But when i try to run this code to fire window scroll only one time with help of true/false variable value but it doesn't work check below what i have tried.

var fired = false;
window.addEventListener("scroll", function() {
    window.scrollY > 30 && fired === false && fetch("https://ip2c.org/self").then((function(t) {
        t.text().then((function(t) {
            t.includes("IND") && (document.getElementById("IN").style.display = "flex")
        }))
    }))
}, true)

Any kind of help or suggestion is highly appreciated.

Is this possible to make window.scrollY fire only onetime.


Solution

  • You're not setting the variable fired to true; besides that,
    the best option would be to use the removeEventListener(eventName, fn):

    const myScrollFetch = () => {
    
      if (window.scrollY <= 30) return; // Do nothing
      
      // Stop listening to scroll event
      window.removeEventListener("scroll", myScrollFetch);
      
      window.scrollY > 30 && fetch("https://ip2c.org/self").then((function(t) {
        t.text().then((function(t) {
          t.includes("IND") && (document.getElementById("IN").style.display = "flex")
        }));
      }));
    }
    
    // Listen to scroll event
    window.addEventListener("scroll", myScrollFetch);