0

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() {
student42
  • 151
  • 1
  • 2
  • 9

3 Answers3

0

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
}
Carsten Løvbo Andersen
  • 22,170
  • 9
  • 42
  • 67
0

Define a named function and set it as the callback for both events.

function callback(){
   // ....
};

$(document).ready(callback);
$(window).resize(callback);
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
0

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.

Luke Stevenson
  • 10,184
  • 2
  • 23
  • 41