Make a simple jQuery plugin

Let’s say you want to implement a textarea that has a logging nature (this is just an example,of course there are real tools out there for javascript logging 😛 )

You can develop a jquery plugin.
For example

(function( $ ) {
  
    $.fn.AreaLogger = function() {
      
        //assign our element to a variable
        var mytextarea = $(this);
        
        if(this.is("textarea")==false) {
            throw { 
                name:        "Jquery Plugin Error", 
                level:       "Logger Initializaition", 
                message:     "Wrong html Element, please give a textarea.", 
                htmlMessage: "Wrong html Element, please give a textarea." 
            }
        }

        //returning a 'logger' element 
        return {
            info: function(message) {
                mytextarea.val(mytextarea.val()+"INFO "+new Date().toString("dddd, mmmm dS, yyyy, h:MM:ss TT")+": "+message+"\n");
            }
        };
    };
})( jQuery );

On your html code you can just write

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Jquery Plugin Test</title>
        <script src="jquery.min.js">
        </script>        
        <script src="ArreaLogger.js"></script>
        <script>
            $(document).ready(function() {            
                
                var areaLogger = $("#logarea").AreaLogger();
                    
                $("#logtest").click(function() {
                    areaLogger.info($("#test").val());
                });
            });
        </script>
    </head>
    <body>
        <input id="test"/>
        </br>
        <textarea id="logarea"></textarea>
        <div id="wut"></div>
        </br>
        <button id="logtest">Test</button>
    </body>
</html>

You can download jquery from here

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.