$ (...). functionName () is not a function - why is this happening and how to avoid it?
3 answers
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>
0
source to share
$.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>
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>
0
source to share