Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a function to jQuery?

Tags:

jquery

What's the easiest way to define a new jQuery member function?

So that I can call something like:

$('#id').applyMyOwnFunc() 
like image 575
Mask Avatar asked Nov 20 '09 03:11

Mask


People also ask

How do you create a function in jQuery?

Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.

How can I call function in jQuery?

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).

What is $( function () in jQuery?

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() { });

What is ADD method in jQuery?

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.


1 Answers

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(); 
like image 66
keyboardP Avatar answered Sep 28 '22 02:09

keyboardP