Associate the function with resizing the window and scrolling the window, but also call it immediately

So, there are some components on the web page that need to be reinstalled when the browser window is resized or scrolled.

$( window ).on( 'resize scroll', reposition ); 

where reposition is the function that does this.

However, this function should also be called immediately. (I immediately mean when initializing the page β€” inside the DOM-ready.) This needs to be done to set up the initial positions of the components.

Now I am doing it like this:

 $( window ).on( 'resize scroll', reposition ); reposition(); 

I noticed that this also works:

 $( window ).on( 'resize scroll load', reposition ); 

I believe this is reliable - load never fires before the DOMContentLoaded event.

But this delays execution until all resources of the page are loaded (which may take several seconds, depending on the number of images on the page). Is there a way to tell jQuery that a related function should also be called immediately?

how

 $( window ).on( 'resize scroll now', reposition ); 

or

 $( window ).on( 'resize scroll ()', reposition ); 

These examples are invalid, of course, but I was wondering if the jQuery on method has this functionality. I suppose that I could manually implement this functionality in on , but I would like to check first if it already has it ...

+4
source share
1 answer

You can do something like this:

 $(window).on('resize scroll', reposition).trigger('scroll'); 

To set and activate an event callback.

Although you should set this to $ (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 are guaranteed that the DOM will be ready for you to mess with

+7
source

Source: https://habr.com/ru/post/1391918/


All Articles