How can I call a global jquery function within document.ready. It generate TypeError: $.myfunction is not a function

StackOverflow https://stackoverflow.com/questions/22644298

Pregunta

When I try to define a global function ( as I know it and I may be wrong, correct me if I am wrong ) I am unable to call the function within document.ready(). This throws an uncaught error TypeError: $.myfunction is not a function Is this due to scope issue or something else? What should I do instead to make it work?

 (function( $ ){
     $.fn.myfunction = function() {
      alert('hello world');
      return this;
     }; 
 })( jQuery );

 $( document ).ready(function() {
     console.log( "ready!" );
     $.myfunction();
 });
¿Fue útil?

Solución

use a selector before calling the function,

 $( document ).ready(function() {
 console.log( "ready!" );
 $(this).myfunction();
 });

Demo

Otros consejos

There is two things you need to know.

fn properties are jQuery Object prototype function, which mean that you can't use functions declare as prototype without a jQuery object.

To create a jQuery object you need to call $. So $('').myFunction() would work.

If you want to use it like that ($.myFunction();), you need to assign a function to the jQuery Object Declaration itself, not its prototype. So that would work :

$.myFunction = function(){...};

If you don't want a selector why not use a normal function instead?

var myfunction = function() {
      alert('hello world');
      return this;
     }

$( document ).ready(function() {
     console.log( "ready!" );
     myfunction();
 });

Note: $.fn.myfunction will not make your function available in the whole project.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top