Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript plugin creation

How to create a pure JavaScript (without using any library) plugin which looks like:

document.getElementById('id').myPlugin();

Like jQuery?

like image 499
Aneesh Avatar asked Apr 26 '10 08:04

Aneesh


People also ask

What is a JavaScript plugin?

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.

How do you add a plugin to HTML?

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.

Can I make WordPress plugin with JavaScript?

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.


1 Answers

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();
like image 110
James Avatar answered Sep 28 '22 03:09

James