Easy jQuery

Blog about jQuery - next generation JavaScript library.

Archive for October, 2008

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
19

jQuery selectors - Part IV.

AlexOther


Attribute Filters.

[attribute] - select all elements that have specified attribute.
This code will select all divs that have attribute id and set red border around them:

$("div[id]").css("border-color", "red");

Open this example in new window and view source code.

[attribute=value] - select all elements that have attribute with certain value.
This code will select input field with name “myinput” and set their value to “abc”:

$("input[name='myinput']").val("abc");

Open this example in new window and view source code.

[attribute!=value] - select all elements that have not specified attribute or have attribute but with other value.
This code will select all divs whith id != 1 and set red border to them:

$("div[id!='1']").css("border-color","red");

Open this example in new window and view source code.

[attribute^=value] - select all elements that have specified attribute and it starts with certain value.
This code will select all input fileds with name starts with “myinput” and set their value to “abc”:

$("input[name^='myinput']").val("abc");

Open this example in new window and view source code.

[attribute$=value] - select all elements that have specified attribute and it ends with certain value.
This code will select all input fileds with name ends with “input” and set their value to “abc”:

$("input[name$='input']").val("abc");

Open this example in new window and view source code.

[attribute*=value] - select all elements that have specified attribute and it contains certain value.
This code will select all divs with id contains word “number” and set red border around them:

$("div[id*='number']").css("border-color","red");

Open this example in new window and view source code.

[attributeFilter1][attributeFilter2][attributeFilterN] - select all elements that match all of the specified attribute filters.
This code will select all inputs that contains attribute id and which name ends with “input” and set their value to “abc”:

$("input[id][name$='input']").value("abc");

Open this example in new window and view source code.


Child Filters.

:nth-child(index/even/odd/equation) - select all elements that are the nth-child of their parent or that are the parent’s even or odd children. Argument can be integer index (staring with 1) or string - “event”, “odd” or equation.
This code will select all seconds <li> of ul’s and set their color to red:

$("ul li:nth-child(2)").css("color","red");

Open this example in new window and view source code.

:first-child - select all elements that are the first child of their parent.
This code will select all firsts <li> of ul’s and set their color to red:

$("ul li:first-child").css("color","red");

Open this example in new window and view source code.

:last-child - select all elements that are the last child of their parent.
This code will select all last <li> of ul’s and set their color to red:

$("ul li:last-child").css("color","red");

Open this example in new window and view source code.

:only-child - select all elements that are the only child of their parent.
This code will select all <li> of ul’s which have no any siblings and set their color to red:

$("ul li:only-child").css("color","red");

Open this example in new window and view source code.

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.

Oct
12

jQuery selectors - Part III.

AlexGeneral


Content Filters.

:contains(text) - select all elements which contain given text.
This code will underline all divs which contain name John:

$("div:contains('John')").css("text-decoration", "underline");

Open this example in new window and view source code.

:empty - select all elements which has no any elements, nodes or texts.
This code will fill all empty cells of table whith text “This was empty!”:

$("td:empty").text("This was empty!");

Open this example in new window and view source code.

:has(selector) - select all elements which has at least one element specified by selector.
This code will add class .test to all divs which contains at least one tag <p>>:

$("div:has").addClass("test");

Open this example in new window and view source code.

:parent - select all elements that are parents (has at least one child element).
This code will select all cells which has child elements and change opacity of its background color:

$("td:parent").fadeTo(1500, 0.3);

Open this example in new window and view source code.


Visibility Filters.

:hidden - select all hidden elements or input fields.
This code will show all hidden divs and count hidden form elements:

$("div:hidden").show(3000);
$("span").text("Found " + $("input:hidden").length + " hidden inputs.");

Open this example in new window and view source code.

:visible - select all visible elements.
This code will set background color to yellow to all divs that are visible (than, we will show hidden divs to ensure that they are not changes color to yellow):

$("div:visible").css("background-color","yellow");
$("div:hidden").show(3000);

Open this example in new window and view source code.

Oct
9

jQuery How-To - Part I.

AlexHow-to

I’m planning to post some jQuery code snippets in this category. It’s usefull to have such a small parts of a code in your personal library and don’t waste time coding or googling it.

How to center element in browser window.

jQuery.fn.center = function() 
{
var w = $(window);
this.css("position","absolute");
this.css("top",(w.height()-this.height())/2+w.scrollTop() + "px");
this.css("left",(w.width()-this.width())/2+w.scrollLeft() + "px");
return this;
}

Now we can just write:

$(element).center();

and object will be centerd.

Open this example in new window and view source code.

How to make entire block of code clickable.

Javascript code:

$(".pane-list li").click(function(){
window.location=$(this).find("a").attr("href");return false;
});

…and some html code:

<ul class="pane-list">
  <li>
   <h3><a href="http://www.jquery.com">jQuery homepage</a></h3>
   <p>This is jQuery homepage</p>
  </li>
  <li>
   <h3>Google</h3>
   <p>This is a best search engine - 
<a href="http://www.google.com">Google!</a></p>
</li>
</ul>

Open this example in new window and view source code.

How to select all checkboxes inside the form.

This function will select all checkboxes in the given element (div, for example). We pass element id as an argument:

function checkall(context){
$("#"+context).find("input[@type=checkbox]").each(function(){
this.checked = "checked";
});
}

In this example only Checkbox #1 and Checkbox #2 will be selected because they are inside div with id “myboxes”:

<script type="text/javascipt">checkall("myboxes");</script>
<div id="myboxes">
	Form #1:<br>
	<form action="" method="GET">
		<input type="checkbox" name="cb1">Checkbox #1
		<input type="checkbox" name="cb2">Checkbox #2
	</form>
</div>
Form #2:<br>
<form action="" method="GET">
	<input type="checkbox" name="cb3">Checkbox #3
	<input type="checkbox" name="cb4">Checkbox #4
</form>

Open this example in new window and view source code.

How to find out quantity of selected elements.

Just like this:

$('element').size();

How to find out if some element present on page.

You can just check length value:

if ( $('element').length ) { /* do something */}
Oct
4

Selectors - Part II.

AlexGeneral


Basic filters.

:first - select first element.
This code will set font to italic on first row of the table:

$("tr:first").css("font-style","italic");

Open this example in new window and view source code.

:last - select last element
This code will select the last row of table and set background color to yellow and font to bold:

$("tr:last").css({
  backgroundColor: "yellow",
  fontWeight: "bolder"
});

Open this example in new window and view source code.

:not(selector) - select all elements which has not filtered by selector.
This code select all spans on the page that have not class “myclass” and set their background color to red:

$(":not(.myclass) + span").css("background-color","red");

Open this example in new window and view source code.

:even - select all even elements, zero-indexed.
This code select all even table rows and set their background color to red:

$("tr:even").css("background-color","red");

Open this example in new window and view source code.

:odd - select all odd elements, zero-indexed.
This code select all odd table rows and set their background color to red:

$("tr:odd").css("background-color","red");

Open this example in new window and view source code.

:eq(index) - select single element by index, zero-indexed.
This code select second cell in a table and set their background color to red:

$("td:eq(2)").css("background-color","red");

Open this example in new window and view source code.

:gt(index) - select elements with index, greater than given one, zero-indexed.
This code select all cells in a table with index greater than 3 and set their background color to red:

$("gt:eq(3)").css("background-color","red");

Open this example in new window and view source code.

:lt(index) - select elements with index, below than given one, zero-indexed.
This code select all cells in a table with index less than 3 and set their background color to red:

$("gt:lt(3)").css("background-color","red");

Open this example in new window and view source code.

:header - select all header on the page (h1, h2, …).
This code select all headers and set their font color to blue:

$(":header").css("color","blue");

Open this example in new window and view source code.

:animated - select all currently animated elements on page.
This code select change color of any div, beeng animated:

$("#run").click(function(){
      $("div:animated").toggleClass("colored");
});
function animateIt() {
      $("#mover").slideToggle("slow", animateIt);
}
animateIt();

Open this example in new window and view source code.