Feel
Feel

Reputation: 51

How to run one javascript function on two different events?

I have one javascript function and I want run it on two diferent events - document.ready and window.scroll. How to do it?

Upvotes: 0

Views: 82

Answers (2)

Momin
Momin

Reputation: 868

call it like

    $(document).ready(function(){
        $(window).scroll(function(){
           //some func
        });
        //same func
    })

also use it like this on onscroll

If u want it on doc.ready too then write 2nd time too(though its not a good idea.)

Upvotes: 1

adeneo
adeneo

Reputation: 318162

Guessing you're using jQuery (document.ready and all).

Attaching the event handler to the window after document.ready, and then triggering the event immediately fires the handler on document.ready and on every scroll event.

$(document).ready(function() {
    $(window).on('scroll', function() {
        // do stuff
    }).trigger('scroll');
});

or to reference a function

$(document).ready(function() {
    $(window).on('scroll', myJavascriptFunction).trigger('scroll');
});

function myJavascriptFunction() {
    // do stuff
}

Upvotes: 3

Related Questions