I'd like this jQuery function to run on resize in addtition to page load.
jQuery(document).ready(function() {
Something like:
jQuery(document).ready OR $(window).resize(function() {
This might be a solution for you.
The function runMyFunction
will run when either the page is ready
or when you resize
the page
$(document).ready(runMyFunction);
$(window).on('resize', runMyFunction);
function runMyFunction() {
// do whatever
}
Define a named function and set it as the callback for both events.
function callback(){
// ....
};
$(document).ready(callback);
$(window).resize(callback);
The recommended syntax for initialising jQuery is NOT to use the .ready()
function.
function toBePerformedOnLoadAndResize(){
// Your code here
}
$(function(){
// The above is the suggested replacement for
// "$(document).ready(function(){
// Run it now
toBePerformedOnLoadAndResize();
// Run it on resize as well
$(window).resize(toBePerformedOnLoadAndResize);
// Your Other Code
});
Source jQuery API documentation:
As of jQuery 3.0, only
$( handler )
is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example,$( "document" ).ready( handler )
works with "document" which selects nothing. The$( "img" ).ready( handler )
waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.