I’m not an expert on this, this is my first foray into creating a jQuery plugin.
What I want to do is create a jQuery plugin that can be called both on a dom object, but also independently.
For example, if my plugin is to alert() something I would like it to be able to be called both ways below:
$.tcAlert('Hello World');
// Resulting code:
//
// alert('Hello World');
//
$('#myDiv').tcAlert();
// Resulting code:
//
// theText = $('myDiv').text();
// alert(theText);
//
Obviously this is a very simple example, but I cannot seem to find any documentation on how to go about creating a plugin like this. Will I, in effect, have to create the jQuery extension and then the jQuery.fn extension references the original extension?
Any help/pointers would be very helpful thank you.
In general, if it’s a function that does something with an element, you should write it in plugin format, e.g.
$.fn.myPlugin = function() {};. If it’s just an utility function, add it to the globaljQuery/$object, e.g.$.myFunction = function() {};Your example could be written as follows: