1

this is kind of a global question :

When you create a custom jQuery function using $.fn.foo = function(){} and let's say we apply this function to $("#foo") just like $("#foo").foo():

How can we refer to $("#foo") in the function independently from its "absolute name" ?

I tried using $(this) but the console spew an error at me : Ignoring get or set of property that has [LenientThis] because the "this" object is incorrect.

2
  • And did you simply try this? Commented Mar 25, 2017 at 11:51
  • Indeed using this solved my problem thx ! Commented Mar 25, 2017 at 11:55

1 Answer 1

1

The jquery site has a good starting point for creating plug-ins: "How to Create a Basic Plugin". It mentions:

... we use this, not $( this ) ...

In the section Using the each method, you'll find a common pattern:

Your typical jQuery object will contain references to any number of DOM elements, and that's why jQuery objects are often referred to as collections. If you want to do any manipulating with specific elements (e.g. getting a data attribute, calculating specific positions) then you need to use .each() to loop through the elements.

$.fn.myNewPlugin = function() { 

   return this.each(function() {
       // Do something to each element here.
   });

};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.