Open In App

jQuery | $.proxy() Method

Last Updated : 19 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
The $.proxy() Method in jQuery accepts an existing function and returns a new one with a particular context. Generally, it is used for attaching events to an element where the context is pointing back to a different object. Syntax:
  • $(selector).proxy(function, context)
  • $(selector).proxy(context, name)
Parameter: This method accepts three parameters as mentioned above and described below:
  • function: It holds the existing function name which is to be called.
  • context: It shows the name of the object where the function lies.
  • name: The function whose context is to be changed.
Example 1: This example displays the context of h3 element. html
<!DOCTYPE html>
<html>
    
<head>
    <title>
        jQuery $.proxy() Method
    </title>
    
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    
    <script>
        $(document).ready(function() {
         
            test = function() {
                this.txt = "Property of Object";
                $("h3").click($.proxy(this.myClick, this));
            };
             
            test.prototype.myClick = function(event) {
                alert(this.txt);
                alert(event.currentTarget.nodeName);
            };
             
            var x = new test();
         
        });
    </script>
</head>

<body style="text-align:center;">
 
    <h1>Welcome to GeeksforGeeks!.</h1> 
    
    <div style="background-color:green">
        <h3>Geeks for Geeks.</h3>    
    </div>
</body>

</html>
Output:
  • Before clicking on the heading text h3:
  • After clicking on the heading text h3:
  • Click on OK button:
Example 2: This example call the objPerson object and display its content. html
<!DOCTYPE html>
<html>
    
<head>
     <title>
        jQuery $.proxy() Method
     </title>
     
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    
    <!-- Script to illustrate $.proxy() Method -->
    <script>
        $(document).ready(function(){
            var objPerson = {
                test: function() {
                    $("h2").after("GeeksforGeeks");
                }
            };
        
            $("button").click($.proxy(objPerson, "test"));
        });
    </script>
</head>

<body style="text-align:center;">

    <h1>Welcome to GeeksforGeeks!.</h1> 
    
    <div style="background-color:green">
        <button>The $.proxy Method.</button>        
        <h2></h2>  
    </div>
</body>

</html>
Output:
  • Before clicking on the button:
  • After clicking on the button:

Next Article

Similar Reads