Call a function onload, and onscroll also?

I have a function which is called when the user scrolls. Works well, but for elements those are on the top of the document (and on the top of the viewport of course), the effects inside the function executes after the first scroll. I need to know if there's a way to do something like this:

if(window.onscroll || window.onload){
    function toExecute(){}

2 answers

  • answered 2018-03-13 20:45 Jacob Morris

    you can easily do for running on javscript and then just also run function on mouseover on an element

    <body onload=“yourfunction name”>
    <p onmouseover=“your function name”>test here</p>

    Then have like this on javascript

    function your function name () {
      alert(“onload or mouseover!”);

  • answered 2018-03-13 20:45 Nit

    The easiest way to do this would be to bind the same function to both the load and the scroll event.
    However, since the scroll handler is called very rapidly and can easily cause performance issues on either mobile devices or older browsers, it's better to debounce the scroll handler.

    function foo() {
      console.log('foo called at ' + new Date());
    let timer;
    function debouncedFoo() {
      if (timer) return;
      timer = setTimeout(() => {
        timer = null;
      }, 20);
    window.addEventListener('load', foo);
    window.addEventListener('scroll', debouncedFoo);
    body {
      height: 3000px;