Search code examples
jqueryfunctiondomtypeerrorreferenceerror

Function within Jquery not being seen


Hey all I have the following function that I am trying to call from a button click:

(function ($) {
  $(window).load(function() { 
     $("#status").fadeOut();
     $("#preloader").delay(400).fadeOut("slow");
     [Lots of code here]
  });

  $(document).ready(function() {
     [Lots of code here]
  });

  [Lots of code here]

  function testing() {
     $("#status").fadeIn();
     $("#preloader").delay(400).fadeIn("slow");
  }

  [Lots of code here]
}(jQuery));

The error I get is:

Uncaught ReferenceError: testing is not defined

The HTML of the button I am using is:

<button value="TEST" onClick="testing();">test</button>

When I try placing the testing() code outside of the (function ($) { }(jQuery)); it doesn't find the values for status and preloader having the error of this below on the $("#status").fadeIn(); line:

Uncaught TypeError: undefined is not a function

I know the issue is around the (function ($) { }(jQuery)); but I am unsure on how to go about being able to call it since this isn't my code.


Solution

  • This happens because testing is inside jQuery scope. Your code should look like this:

    function testing() {
       jQuery("#status").fadeIn();
       jQuery("#preloader").delay(400).fadeIn("slow");
    }
    (function ($) {