How to create a pure JavaScript (without using any library) plugin which looks like:
document.getElementById('id').myPlugin();
Like jQuery?
A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods.
Plug-ins can be added to web pages with the <object> tag or the <embed> tag. Plug-ins can be used for many purposes: display maps, scan for viruses, verify your bank id, etc. To display video and audio: Use the <video> and <audio> tags.
The answer is no, you cannot, as you have referenced in your question. By definition, a plugin is at the very least a "PHP file with a WordPress plugin header comment" (Wordpress Docs). However, there is no reason a Wordpress plugin can't be primarily Javascript.
You can create your own wrapper (similar to jQuery), and doing this will allow you to circumvent all of the discussed problems with extending the DOM directly.
myWrapper = (function(){
function NodeList(elems) {
this.length = 0;
this.merge(this, elems.nodeType ? [elems] : elems);
}
function myWrapper(elems) {
return new NodeList(elems);
}
myWrapper.NodeList = NodeList;
NodeList.prototype = {
merge: function(first, second) {
var i = first.length, j = 0;
for (var l = second.length; j < l; ++j) {
first[i++] = second[j];
}
first.length = i;
return first;
},
each: function(fn) {
for (var i = -1, l = this.length; ++i < l;) {
fn.call(this[i], this[i], i, l, this);
}
return this;
}
};
return myWrapper;
})();
And you can add your own methods like so:
myWrapper.NodeList.prototype.myPlugin = function() {
return this.each(function(){
// Do something with 'this' (the element)
});
};
Usage:
myWrapper(document.getElementById('id')).myPlugin();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With