JavaScript · jQuery · Programming

A very simple jQuery plugin

A very simple plugin that changes the background color of an element on click.

Plugin Code
This is saved in a js file called myPlugin.js

(function($) 
  {
    //default options
    var defOption = {"bg":"#f00"};
    var finalOpt = {};

    function makeBgRed(obj)
    {
      obj.style.backgroundColor = finalOpt.bg;
    }
    
    $.fn.myPlugin = function(option) {
      
      //util functions
      finalOpt = $.extend(defOption,option);

      //here 'this' is the jQuery because jQuery is the enclosing scope
      return this.each(function(){
        
        //in here 'this' is a DOM node so we will have wrap it inside $ to make it a jquery object
        $(this).bind('click',null,function(){

          makeBgRed(this);
          
        });
      
      });
      
      
    };
    
  }

)(jQuery);

HTML Code

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <p id="hello">Hello World</p>
  <script>
    $(document).ready(
      
      function() {
        var opt = {"bg":"#ccf"};
                   
        $('p').myPlugin(opt);
      }
      
    );
  </script>
  <script src="myPlugin.js"></script>
</body>
</html>
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s