$ (...). functionName () is not a function - why is this happening and how to avoid it?

I am getting console error

$ (...). functionName () is not a function


This is my function call

$("button").functionName();

      


This is my function

$.fn.functionName = function() {
       //Do Something
}(jQuery);

      


Why does this error occur and how can I avoid this error?

+3


source to share


3 answers


try using the following syntax:



jQuery.fn.extend({
    functionName: function () {

    }
});

      

0


source


Remove (jquery)

from your code,



$.fn.functionName = function() {
       //Do Something
       alert('worked');
};

$("button").functionName();
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Button</button>
      

Run codeHide result


0


source


$.fn.functionName = function() {
       //Do Something
}(jQuery);

      

These are self-executing functions. The advantage of self-executing functions is that it allows you to execute code once without cluttering the global namespace (without declaring any global variables).

$.fn.functionName = function() {
  alert('Immediately Invoked');
}(jQuery);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<button> Button </button>
      

Run codeHide result


If you run the previous piece of code, it will automatically call the function and alert the message

without calling the function.


To fix the problem, you need to remove (jQuery) so you can use this function:

$.fn.functionName = function() {
    this.css('color', 'red');
}
 
$( "button" ).functionName();
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Button 1</button>
<button>Button 2</button>
      

Run codeHide result


0


source







All Articles