Question

I have a function, for example:

$(window).scroll(function(e){
 // my stuff
});

Is there a way to call the function directy after the init? I know this syntax to call a function directly after the init:

(function(){
 // this function will be called directly
})();

but how can I adjust my code to do the same (call the scroll-function directly one time after it was initialized)?

Was it helpful?

Solution

You can trigger() the event handler immediately

$(window).scroll(function(e){
 // my stuff
}).trigger('scroll');

EDIT:

per the comments, to make sure no other scroll event handlers are triggered, you can namespace the event

$(window).on('scroll.custom', function(e) {
 // my stuff
}).trigger('scroll.custom');

OTHER TIPS

Can you not simply name the function before hand and call the function immediately -

function myHandler(e){
// your stuff
};
// add handler to event
$(window).scroll(myHandler);
// call first time
myHandler();
// Pass necessary params as you need
// Will not trigger any other event handlers

Does this help?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top