Search code examples
javascriptfunctioneventsonloadonscroll

How to assign some one function to several events?


Maybe it is dumb question, but how can I do something like this in JavaScript:

document.onload = function() { typeText(); }
window.onscroll = function() { typeText(); }

function typeText() { ... }

?

P.S.: Actually, this example doesn't work.


Solution

  • Like this:

    function typeText() { ... }
    
    document.onload = typeText;
    window.onscroll = typeText;
    

    If you'd also like to pass in parameters, I'd recommend looking at the .bind() method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    But an example would look like this:

    document.onload = typeText.bind(this, param1, param2);