How to execute a function on load, resize and scroll event in jQuery?

In jQuery we can very easily bind load, resize and scroll events and run a function. The global window object has those events available. When we use jQuery then we can use jQuery wrapper methods to fire those events.

Following are different ways of executing a function on load, resize and scroll events:

The load event

$(window).load(function () {
    // define the function here
});

The resize event

$(window).resize(function () {
    // define the function here
});

The scroll event

$(window).scroll(function () {
    // define the function here
});

We can combine all the events using jQuery on method. The method on binds all the events and allows one callback:

$(window).on("load resize scroll",function(e){
    // define the function here
});

If we want to separate the callback function for each event using on method we can do the following:

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

We can also use bind method to combine all the events:

$(window).bind("load resize scroll",function(e){
    // define the function here
});

If we want to separate the callback function for each event using bind method we can do the following:

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});
Share