Easy jQuery

Blog about jQuery - next generation JavaScript library.

Archive for the ‘How-to’ 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
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 */}
Sep
30

Some interesting facts about jQuery.

AlexGeneral, How-to

1. When you add some handler for the event - it does no replace previous handler . So both handlers will run.

In this example, if you click on element with id “example” - you will see both alerts:

$('#example').click(function(){ alert('one'); } );
$('#example').click(function(){ alert('two'); } );

2. Basing on previous fact we can do next conclusion - you can use function

$(document).ready();

as many times as you want in your page.

3. You can create your own events in jQuery. This method allow make your code more simple and readable.

$('button').click(function(){ jQuery.event.trigger('buttonClicked'); });
$('div').bind('buttonClicked',function(){ $(this).hide(); });
$('span').bind('buttonClicked',function(){ $(this).show(); });

4. Annimation effects in iQuery is asynchronous so question “how to excecute one function exactly after another” can appears very often. But all animation core-functions of jQuery receive callback function as a last argument.

$('element-1').fadeOut(3000,function() {
                        $('element-2').fadeIn(1500,function() {
                            alert('done second effect');
                        });
});

5. You can add any attribute to any html-element:

<span myownattr="somevalue" />

and match them using jQuery selectors:

var elements_by_attr = $('[@myownattr]');
var elements_by_attr_with_value = $('[@myownattr="somevalue"]');
var spans_by_attr = $('span[@myownattr]');