Easy jQuery

Blog about jQuery - next generation JavaScript library.

Archive for the ‘Plugins’ Category

Nov
16

jQuery Corner plugin.

AlexHow-to, Plugins

I would like to tell you about one outstanding plugin - jQuery Corner. With this plugin you can easy draw different styles corners. You can draw rounded, with different radius corners, shaped corners, you can apply different styles to different corners.

For using this plugin you should include jQuery library and plugin file:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.corner.js"></script>

And here is the most simple example of using this plugin, which make round corners for div with id #example:

<script type="text/javascript">
$(document).ready(function() {
  $("#example").corner("round");
});
</script>

Open example with different style corners in separate window and view source code.

Using keywords top, bottom, tl, tr, bl, br you can change view only for some of corenrs:

  $("#example").corner("cool tl br");

Open this example in separate window and view source code.

Changing size of corners in pixels is also very easy:

  $("#example").corner("5px");

Open this example in separate window and view source code.

Using “chains” you can apply different styles of corners to the same element:

  $("#example").corner( "br top").corner("notch bl 20px");

Open this example in separate window and view source code.

You can download plugin source code from it home page: jQuery corner source code

Oct
23

How to write jQuery plugin.

AlexHow-to, Plugins

For better understanding of plugins writing technique let’s choose any simple task having at least some practical value. Let’s write jQuery plugin which set different colors for odd and even table rows. Besides, we should have ability to pass font and background colors values for odd and even rows as an arguments. It will be better if we can change font and background colors during mouse movement over the table row. The task is defined so let’s start!
First of all we should remember the main rules of the jQuery plugins writing:

  • plugin filename should be look like this: jquery.[plugin_name].js;
  • all new methods should be attached to jQuery.fn object, all functions should be attached to the jQuery object;
  • this - it’s a refference to the current jQuery object;
  • any functions or methods that you attached shoud have semicolon at the end, or the code can breaks during compression;
  • method should return jQuery object unless you notice about other return value;
  • you should use this.each for iterating over current set of elements;
  • always use jQuery instead of $ sign in your code, that allow users to change pseudonym for jQuery in one place.

Folowing the first rule let’s call our plugin file jquery.stripy.js and first thing that we write there will be plugin definition:

jQuery.fn.stripy = function() {
  // place for our code
};

Now, we can call it like this:

$("selector").stripy();

Our plugin should be able to receive some arguments, so let’s modify our code a bit:

jQuery.fn.stripy = function(options) {
  // place for our code
};

where options - is an object that can contain user settings. But we should define default settings also, because user can ignore our plugin’s arguments.
We should use jQuery.extend(object) for this purpose.

jQuery.fn.stripy = function(options) {
 
  // default settings
  var options = jQuery.extend( {
    background_even: '#FFC080', // background color for even rows
    background_odd: '#FFDFBF', // background color for odd rows
    font_even: '#AA7239', // font color for even rows
    font_odd: '#AA7239', // font color for odd rows
    background_hover: '#FF8000', // hover background color
    font_hover: '#55391C' // hover font color
  },options);
 
  // place for our code
 
};

Options - is an object, consisting of key/value pairs which contains plugin settings. If no settings is specified - we will use default settings. If user will send some options (or all options) to our plugin - we will use exactly them.

Now, we should remember two plugin writing rules more. We need iterate over current elements set and return jQuery object. Let’s do it:

jQuery.fn.stripy = function(options) {
 
  // default settings
  var options = jQuery.extend( {
    background_even: '#FFC080', // background color for even rows
    background_odd: '#FFDFBF', // background color for odd rows
    font_even: '#AA7239', // font color for even rows
    font_odd: '#AA7239', // font color for odd rows
    background_hover: '#FF8000', // hover background color
    font_hover: '#55391C' // hover font color
  },options);
 
  return this.each(function() {
   // place for our code
  });
 
};

We know that this - it is a refference to the current jQuery object. In our case this contains object refference that defined by our plugin user in jQuery selector, for example:

$("table.my").stripy();

In this example, jQuery object contains table or tables with my class.

Now we should write code that realize our functionality.
First of all, let’s find even rows:

jQuery(this).find('tr:even');

We need to set background and font colors for our rows, let’s use css-properties background-color and color for this:

jQuery(this).find('tr:even')
            .css('background-color', options.background_even)
            .css('color', options.font_even);

We setting up css-properties background-color и color for all rows in current elements set (it’s even rows of our current table) getting it from options object.

Let’s process mouse movement over table row:

jQuery(this).find('tr:even')
            .css('background-color', options.background_even)
            .css('color', options.font_even)
            .hover(
              function() {
        	jQuery(this)
                 .css('background-color', options.background_hover)
                 .css('color', options.font_hover);
              },
             function() {
              jQuery(this)
                .css('background-color', options.background_even)
                .css('color', options.font_even);
             }
            );

We use hover() method from jQuery library, first argument - function, that set up css-properties during mouse pointer moving over the row and second argument - function, that return old values when mouse pointer moving out of the row.

Finally, we should add same code for odd rows and here is our plugin:

jQuery.fn.stripy = function(options) {
 
  // default settings
  var options = jQuery.extend( {
    background_even: '#FFC080', // background color for even rows
    background_odd: '#FFDFBF', // background color for odd rows
    font_even: '#AA7239', // font color for even rows
    font_odd: '#AA7239', // font color for odd rows
    background_hover: '#FF8000', // hover background color
    font_hover: '#55391C' // hover font color
  },options);
 
  return this.each(function() {
    //even rows
    jQuery(this).find('tr:even')
            .css('background-color', options.background_even)
            .css('color', options.font_even)
            .hover(
              function() {
        	jQuery(this)
                 .css('background-color', options.background_hover)
                 .css('color', options.font_hover);
              },
             function() {
              jQuery(this)
                .css('background-color', options.background_even)
                .css('color', options.font_even);
             }
            );
 
    //odd rows
    jQuery(this).find('tr:odd')
            .css('background-color', options.background_odd)
            .css('color', options.font_odd)
            .hover(
              function() {
        	jQuery(this)
                 .css('background-color', options.background_hover)
                 .css('color', options.font_hover);
              },
             function() {
              jQuery(this)
                .css('background-color', options.background_odd)
                .css('color', options.font_odd);
             }
            );
 
  });
 
};

So now we have small but working plugin. But we should do another one important thing - write documentation for our plugin.

About jquery.stripy.js plugin.

Plugin jquery.stripy.js allow you easy change font and background colors for odd and even table rows and also change row color under the mouse pointer. Plugin is compatible with IE 6.0+, FF 2+, Safari 2.0+, Opera 9.0+.

Installation.

Include jQuery library and plugin files:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.stripy.js"></script>

Usage.

1. Plugin usage with default settings.

<script type="text/javascript">
$(document).ready(function() {
    $("table.my_class").stripy();
});
</script>

In this example plugin work with table (or tables) which has my_class class. Different css-rules will be applied to the odd and even table rows, as a result they will have different font and background colors.

2. Plugin usage with user settings.

<script type="text/javascript">
$(document).ready(function() {
    $("table.my_class").stripy({
      background_even: '#CC66CC',
      background_odd: '#E6ACE6', 
      font_even: '#662266', 
      font_odd: '#662266', 
      background_hover: '#331133', 
      font_hover: '#FFFFFF' 
    });
});
</script>

In this example we pass object with user settings to plugin as an argument.

Available options.

background_even - string: background color for even rows.
background_odd - string: background color for odd rows.
font_even - string: font color for even rows.
font_odd - string: font color for odd rows.
background_hover - string: background color during mouse pointer moving over row.
font_hover - string: font color during mouse pointer moving over row.

Demonstration.

Demo is available here.

Here you can download demo source code with all needed files.

That’s all! Now you know how to write your own jQuery plugin. Enjoy!

Oct
13

Date Input - jQuery date picking plugin.

AlexPlugins

In this post I would like to tell about jQuery Date Input plugin, which allow user to pick up date from calendar in a couple of clicks. This plugin has a lot of advantages:

  • very simple to implement;
  • small;
  • fast;
  • pretty by default;
  • already localized on more than 20 languages;
  • easy customizable.

To use this plugin you should include jQuery library and plugin file:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.date_input.js"></script>

Include CSS file:

<link rel="stylesheet" href="date_input.css" type="text/css">

Now you should initialize plugin. There are two ways to do it.

  • you can give class “date_input” to all your date input controls and call this function:
    $($.date_input.initialize);
  • or you can call date_input function like this:
    $("#input_control").date_input();

    where “input_control” is id of your input control.

You can change first day of the week:

$(el).date_input({ start_of_week: 0 });

where 0 is Sunday, 1 is Monday etc.

From plugin home page you can download include files with localization for your language and include it too. If there is no localization for your language you can easy translate month names, short month names and short day names, put it in separate file and include it in your page. For example, localization for Spanish language looks like this:

jQuery.extend(DateInput.DEFAULT_OPTS, {
 month_names: ["Enero", "Febrero", "Marzo",
               "Abril", "Mayo", "Junio",
               "Julio", "Agosto", "Septiembre",
               "Octubre", "Noviembre", "Diciembre"],
  short_month_names: ["Ene", "Feb", "Mar", "Abr",
                      "May", "Jun", "Jul", "Ago",
                      "Sep", "Oct", "Nov", "Dic"],
  short_day_names: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sab"]
});

You can also change default date format. If you want to do this - you should replace two plugin functions by your own: stringToDate, which takes a string and returns a Javascript Date object, and dateToString which takes a Javascript Date object and returns a string.
On plugin home page you can find how to replace function to present date in format YYYY-MM-DD.
But I’ll show you how present date in format DD/MM/YYYY:

$.extend(DateInput.DEFAULT_OPTS, {
  stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{2,2})\/(\d{2,2})\/(\d{4,4})$/)) {
      return new Date(matches[3], matches[2] - 1, matches[1]);
    } else {
      return null;
    };
  },
 
  dateToString: function(date) {
    var month = (date.getMonth() + 1).toString();
    var dom = date.getDate().toString();
    if (month.length == 1) month = "0" + month;
    if (dom.length == 1) dom = "0" + dom;
    return dom + "/" + month + "/" + date.getFullYear();
  }
});

And, finally:

Open this example in new window and view source code.

Sep
28

MaskedInput and AlphaNumeric - jQuery plugins for controlling form fields input.

AlexPlugins

One of the often appearing tasks during making user interface for website is the control of the data, entered by users into the input fields. For example, phone number, SSN, date should has certain format.
Masked input plugin allow you easy control what user can enter in input field on client side. Of course, it should not replace serever-side checking, you have to use both methods together but this is other theme to talk about.
This plugin allow you to use alpha, numeric and alphanumeric characters, to change placeholders and to execute a function once the mask has been completed, if needed.
Detailed description of this plugin you can find on the it homepage, but I can show you just a small example:

Including jQuery library and plugin:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.maskedinput.js"></script>

Calling the mask function for those items you wish to have masked:

jQuery(function($){
   $("#phone").mask("(999) 999-9999");
   $("#date").mask("99/99/9999",{placeholder:" "});
   $("#ssn").mask("999-99-9999",{completed:function(){
              alert("You typed the following: "+this.val());}});
})

..and HTML code:

<form method="get" id="example" action="" />
<input type="text" id="phone" /><br />
<input type="text" id="date" /><br />
<input type="text" id="ssl" /><br />
</form>

Open this example in separate window and view source code.

This plugin is good if you know how many characters exactly user shoud enter. But sometimes you need to allow or restrict user to enter variable quantity of certain characters. Another one great plugin, jQuery AlphaNumeric allow you to resolve this task. It allow you to use alpha, numeric or alphanumeric characters, some special characters, like dots, you can also allow or restrict using caps letters.
Another one example:

Including jQuery library and plugin:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.alphanumeric.js"></script>

Calling functions for items you want to control:

jQuery(function($){
$('#alphanum').alphanumeric();   //allow only alpha and numeric characters
$('#alphanocaps').alpha({nocaps:true}); //allow only alpha lowercase characters
$('#numwithdot').numeric({allow:"."});  //allow numeric characters and dots
})

..and HTML code:

<form method="get" id="example" action="" />
<input type="text" id="alphanum" /><br />
<input type="text" id="alphanocaps" /><br />
<input type="text" id="numwithdot" /><br />
</form>

Open this example in separate window and view source code.

I think that usage of Masked Input and jQuery AlphaNumeric plugins is completely enough for handling the task of controlling the characters that the user can input in form fields.