jQuery | $.proxy() Method
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.
<!DOCTYPE html> < html > < head > < title > jQuery $.proxy() Method </ title > < script src = </ 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.
<!DOCTYPE html> < html > < head > < title > jQuery $.proxy() Method </ title > < script src = </ 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:
Please Login to comment...