What's the easiest way to define a new jQuery member function?
So that I can call something like:
$('#id').applyMyOwnFunc()
Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.
You need to use the script tag. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. If you want an event to work on your page, you should call it inside the $(document).
jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });
jQuery add() Method The add() method adds elements to an existing group of elements. This method adds elements on the whole document, or just inside context elements if the context parameter is specified.
Please see "Defining your own functions in jQuery" by Basil Goldman:
In this post, I want to present how easy define your own functions in jQuery and using them.
Modified, based on the code in the blog post linked above:
jQuery.fn.yourFunctionName = function() { // `this` is the jQuery Object on which the yourFunctionName method is called. // `arguments` will contain any arguments passed to the yourFunctionName method. var firstElement = this[0]; return this; // Needed for other methods to be able to chain off of yourFunctionName. };
Just use:
$(element).yourFunctionName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With