I want to create a function or method that can be run on jQuery objects. See jsfiddle.
$(function() {
$("#myElem").click(function(){
$(this).myMethod("red");
});
var myMethod = function(myParam){
var buttonBorder = "2px solid " + myParam;
$(this).css("border", buttonBorder);
};
});
The first problem is that the method isn’t working as I expected. I get this error:
Uncaught TypeError: Object [object Object] has no method 'myMethod'
The second problem (perhaps caused by the first?) is that $(this) in myMethod is not the same as $(this) in the event handler. Is there a way for the method to get the object without explicitly passing it as a parameter?
If you want to create a plugin you have to add it to
jQuery.fn:Now you can call it the way you want to and
thiswill also reference the right context.See the updated fiddle.