Skip to content
Related Articles

Related Articles

Improve Article

How to define jQuery function ?

  • Last Updated : 19 Feb, 2020

Defining the function in jQuery is different from JavaScript, the syntax is totally different. A function is a set of statements that takes input, do some specific computation and produce output. Basically, a function is a set of statements that performs some specific task or does some computation and then return the result to the user.
The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function.

Syntax:

$.fn.myFunction = function(){}

Below examples illustrate the function definition in jQuery:

Example 1:




<!DOCTYPE html> 
<html
  
<head
    <title>
        How to Define jQuery function ?
    </title
      
    <script src=
    </script>
      
    <script>
        $(document).ready(function() {
            $.fn.myFunction = function() { 
                document.getElementById("geeks").innerHTML
                    = "JQuery function is defined!";
            }
              
            $(".gfg").click(function(){
                $.fn.myFunction();
            });
        });
    </script>
</head
  
<body style="text-align:center"
  
    <h1 style="color:green;"
        GeeksforGeeks 
    </h1
      
    <h3>
        Defining function in jQuery
    </h3
      
    <p id="geeks"></p>
      
    <button type="button" class="gfg">
        Click
    </button>
</body
  
</html>        

Output:

Example 2:




<!DOCTYPE html> 
<html
  
<head
    <title>
        How to Define jQuery function ?
    </title
      
    <script src=
    </script>
      
    <script>
        $(document).ready(function() {
            $.fn.myFunction = function() { 
                alert('JQuery function is defined!'); 
            }
            $(".gfg").click(function(){
                $.fn.myFunction();
            });
        });
    </script>
</head
  
<body style="text-align:center;"
      
    <h1 style="color:green;"
        GeeksforGeeks 
    </h1
      
    <h3>
        Defining function in jQuery
    </h3
      
    <button type="button" class="gfg">
        Click
    </button>
</body
  
</html>       

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :