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

    //default options
    var defOption = {"bg":"#f00"};
    var finalOpt = {};

    function makeBgRed(obj)
    { =;
    $.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




<!DOCTYPE html>
<script class="jsbin" src=""></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src=""></script>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
  <p id="hello">Hello World</p>
      function() {
        var opt = {"bg":"#ccf"};
  <script src="myPlugin.js"></script>

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s