0

I have one issue that is a recurring thing every time I work in Javascript, which is that my code seems to be cutting in and out, depending on whether I scroll, resize the screen, reload, etc. It even seems like the speed of which I scroll seems to be a factor (even though I am, in this situation, trying to create a scroll effect, which does work as long as I scroll slowly). I have tried to figure out work arounds almost constantly since starting coding JS, but I can’t even figure out why any of this is happening, and I don’t even know what to good to find the answers.

Generally, when I create functions, I try to use the following structure

document.addEventListener("click", function functionName() {
  /* function content */
});

However, this really only seems to work with click effects, and maybe hover. for scroll effects, because resizing the screen will cause weird things to happen, I have tried using the following structure

function functionName() { /* function content */ };

document.addEventListener('scroll', functionName);
window.addEventListener('load', functionName);
window.addEventListener('resize', functionName); 

This generally works better, and generally prevents screen resizing from interfering too much with scroll effects. However, it makes the code what I am seeing very jumpy and glitchy.

Is there a better way to do this, so that I am a scroll effect will always appear how it should, regardless of whether the screen resizes loads or scrolls, etc.? also, it there a way to make the code work better without having three separate event listeners to activate a single function?

Phil
  • 157,677
  • 23
  • 242
  • 245

2 Answers2

0

The challenge you are running into for other events is that they can be called 10s or 100s of times per second. What you need is to throttle the functions you are calling, especially if they are expensive.

I suggest you look at makeThrottleFn in my xuu library. You might just install it and test like so:

const throttleFn = xuu._makeThrottleFn_({
  _fn_ : onResizeFn, _delay_ms_: 250
});

// And now use this for windowresize
window.addEventListener('resize', throttleFn);

Of course there are many other libraries that offer throttling, so feel free to go shopping.

Michael Mikowski
  • 1,269
  • 1
  • 10
  • 21
-2

Using document.addEventListener("click") is going to run the function anytime the screen is clicked or touched. And applies to the whole document. Meaning anywhere you click the event listener is going to run.

Using the scroll event is running the block of code multiple times. This will create undesired results unless you put in something to stop it. So using multiple document.addEventListeners with "click" and "scroll" will most likely overlap in some cases causing wierd things to happen with both functions running multiple time or randomly.

Mritz
  • 1
  • 2