Home > Back-end >  Why can't I pass $ jQuery object as an argument in window.onload event's handler?
Why can't I pass $ jQuery object as an argument in window.onload event's handler?

Time:09-27

Since the global $ shortcut for jQuery isn't available in WordPress, one must pass $ into the function call. Passing $ to window.onload's event handler however yields the error:

Uncaught TypeError: $ is not a function

Legal:

jQuery(document).ready(function($){
      //jQuery code
})

Illegal:

jQuery(window).on("load", function($){
      //jQuery code
})

Is this a result of window.onload event being a pure javascript event in the DOM and document.ready being a jQuery method?

CodePudding user response:

Compare the documentation for .ready() with .load() and you will find an interesting paragraph for .ready:

Aliasing the jQuery Object

When $.noConflict() is used to avoid namespace conflicts, the $ shortcut is no longer available. However, the .ready() handler is passed a reference to the jQuery object that called the method. This allows the handler to use a jQuery object, for example as $, without knowing its aliased name:

jq2 = jQuery.noConflict();
jq2(function( $ ) {
  // Code using $ as usual goes here; the actual jQuery object is jq2
});

This means .ready has this convenience built in to pass jQuery as the first argument while .load has not.

You can simply console.log($); the parameter to find out what it is. The documentation also tells you.

What you did was naming the first parameter $, which is valid JavaScript. But this does not pass jQuery into the function. It will just name the first parameter $. The error message rightfully points out that it is not a function.
What the parameters for a function are can be read in their documentation.

Links:

  • Related