Reputation: 185963
So, on a web-page there are some components that have to be re-positioned whenever the browser window is re-sized or scrolled.
$( window ).on( 'resize scroll', reposition );
where reposition
is the function that does that.
However, that function has to be invoked immediately too. (By immediately, I mean on page initialization - inside DOM-ready.) This needs to be done to set up the initial positions of the components.
I'm currently doing it like so:
$( window ).on( 'resize scroll', reposition );
reposition();
I noticed that this also works:
$( window ).on( 'resize scroll load', reposition );
I believe this is reliable - the load
is never fired before the DOMContentLoaded
event.
But this delays the execution until after all page resources have been loaded (which could take a few seconds depending on how many images there are on the page). Is there any way to tell jQuery that the bound function should be invoked immediately too?
Like:
$( window ).on( 'resize scroll now', reposition );
or
$( window ).on( 'resize scroll ()', reposition );
These examples are of course invalid, but I was wondering if jQuery's on
method has such functionality. I guess, I could manually implement this functionality into on
, but I'd like to first check if it has that already...
Upvotes: 4
Views: 10950
Reputation: 35284
You can do something like this:
$(window).on('resize scroll', reposition).trigger('scroll');
To set and trigger an event callback.
Although you should be setting this in the $(document).ready just to be safe. Basically your code should look something like this:
$(document).ready(function() {
$(window).on('resize scroll', reposition).trigger('scroll');
});
So you're guaranteed that the DOM will be ready for you to mess around with
Upvotes: 7