Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Monday, March 4, 2013

jQuery datepicker range : Select date with From and To.

    jQuery datepicker is one the sophisticated ui components jQuery provides. There are loads of options to customize the datepicker as per your needs. Generally it's used on a text field, which when clicked opens an interactive calendar. User selects a date and input field gets filled with the date in appropriate date format as per our configuration. 

  There are many uses of this kind of datepicker. One of them is to select a range of dates with structure like select date From and select date To. Just the way shown below :


Datepicker range
   
     Creating this kind of range datepickers in jQuery is very easy. You need to use onSelect callback function along with minDate and maxDate. The idea is that when user selects "from" date, the selected date is set as minDate for "to" datepicker. And when user selects "to" date, the selected date is set as maxDate for "from" datepicker. This enables user to select a date in appropriate range only and you need not to perform any range validation like say "to" is not older than "from". 

    Consider "from" and "to" are ids of from and to datepicker's text fields. I believe you have included js files for jQuery and jQuery UI along with css file of UI. The code snippet looks like this : 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 $( "#from" ).datepicker({
      changeMonth: true,  
      changeYear:true,      
      maxDate:0,
      onSelect: function( selectedDate ) {
        $( "#to" ).datepicker( "option", "minDate", selectedDate );
      }
    });
    $( "#to" ).datepicker({      
      changeMonth: true,   
      changeYear:true,
      maxDate:0,
      onSelect: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });


    Please take note of how onSelect function is used and how minDate and maxDate are set. 
    Setting maxDate to 0 (today) is used to prevent user from selecting date larger than today's date, this is used mainly because range datepickers are generally used to select date from past like selecting range for showing history logs, college years etc. You can use or remove that as per your needs.

   This fiddle shows how it works : 




Saturday, October 27, 2012

jQuery - Difference between :eq() and :nth-child() selectors.


    In jQuery many times :nth-child(n)  pseudo-class selector is easily confused with :eq(n), even though the two can result in dramatically different matched elements.

   With :nth-child(n), first all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the nth one is selected.

    In other worlds, with :nth-child(n), first all elements those are children are considered and among the children, nth child is considered then it’s checked if it matches the selector which is attached with :nth-child(n). On the other hand with :eq(n) first the attached selector is resolved to set of elements and among those elements nth element is selected independent of considering children or not.


    Also there is another important difference, that is :nth-child() is 1 indexed means indexing count starts with 1 so nth means actual nth one. While :eq() is 0 indexed with indexing starting with 0 so nth element is actually (n+1)th. This is so because jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification and for all other selector expressions including :eq() however, jQuery follows JavaScript's "0-indexed" counting. 

   Let's see following simple example: 


<table>
          <tr><td>Table1-row1</td></tr>
          <tr><td>Table1-row2</td></tr>
          <tr><td>Table1-row3</td></tr>
</table>
<table>
          <tr><td>Table2-row1</td></tr>
          <tr><td>Table2-row2</td></tr>
          <tr><td>Table2-row3</td></tr>
          <tr><td>Table2-row4</td></tr>
</table>

In above tables $(“tr:nth-child(3)”) will select two elements :


         <tr><td>Table1-row3</td></tr>
And

        <tr><td>Table2-row3</td></tr>

While $(“tr:eq(3)”) will select only single element :


        <tr><td>Table2-row1</td></tr>
   
 Please try following fiddle also, run it and click a button to see what it selects. It also shows how :even and nth-child(even) are different.






Saturday, April 21, 2012

How to create your own jQuery plugin !

Once you know jQuery, it’s simple to create your own plugin. Depending on the complexity of your plugin, you need to take care of following steps. For learning purpose it’s good to go step by step and know why do we do what we do for creating your own plugin.

1. Cross Library Safety :

(function($){

//Here $ means jQuery

})(jQuery)

This will mean $ in that particular function is jQuery, so that there will be no conflict when you or someone else is using your jQuery plugin along with other java script libraries which may use $ for their own purpose.

2.Adding function property to the jQuery.fn object :

Here you will add your plugin to $fn object as a property which makes your plugin usable. Use your plugin name here.

(function( $ ) {
  $.fn.myPlugin = function() {
  
    //your plugin stuff here

  };
})( jQuery );

3.this is a  available object :

this variable  is available directly inside your function code so …
 this.fadeIn() works here, 
so no need to use $(this) for simple plugins.

4.Better use each to iterate over elements given by Selector :

this.each(function() {
        ///Some code here
    });
so that the selector on which your plugin is called when selects multiple elements, this will get applied to all of them.

5.To maintain chainability the plugin should return this keyword :


return this.each(function(parameters) {
         var $this = $(this);
      //code using $this 
    });

So hence forth you will be using $(this), through say variable $this.
Chainability allows to perform some actions on the same element(s) one by one, which simplifies the way your plugin would be used.



6. Multiple options with default values :

For more complex plugins providing multiple attributes, it’s better to provide default values for attributes..

(function( $ ){

  $.fn.tooltip = function( options ) {  
    // Create some defaults, extending them with any options that were provided
    var settings = $.extend( {
      'location'         : 'top',
      'background-color' : 'blue'
    }, options);

    return this.each(function() {        
//use settings[“location”]  or settings.location
      // Tooltip plugin code here
    });
  };
})( jQuery );

Calling it

$('div').tooltip({
  'location' : 'left'
});

 So if you have provided default options, you can use those in your code, now it's not necessary for user to provide values for all the attributes.

Here $.extend is used which accepts two object, here first one will be default values object and second one will be one provided by the user with his values. $.extend will merge second object into first, so that if values for some options are not provided then it will take default ones.

7.Multiple Methods in plugin with NAMESPACING :

(function( $ ){

  var methods = {
    init : function( options ) { 
      // code
    },
    show : function( ) {
      // code    },
    hide : function( ) { 
      // code
    },
    update : function( content ) { 
      // code    }
  };

  $.fn. myPlugin = function( method ) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
  
  };

})( jQuery );

// calls the init method
$('div'). myPlugin (); 

// calls the init method
$('div'). myPlugin ({
  foo : 'bar'
});

Call these methods by first passing the string name of the method, and then passing any additional parameters you might need for that method. This type of method encapsulation and architecture is a standard in the jQuery plugin .

Calling this,

$('div'). myPlugin ('hide'); 
$('div'). myPlugin ('update', 'This is the new myPlugin content!'); 

8.Bind an event :
If you want your plugin to bind an event, use following way (please namespace it )
And have a method like destroy as shown below to unbind what is "bind" earlier.

init : function( options ) {

       return this.each(function(){
         $(window).bind('resize.myPlugin', methods.reposition);
       });

     },
     destroy : function( ) {

       return this.each(function(){
         $(window).unbind('. myPlugin ');
       })

     },
     reposition : function( ) { 
       // ... 
     },
$('#fun'). myPlugin ();
// Some time later...
$('#fun'). myPlugin ('destroy');


So now decide on your plugin idea and start writing it.
Best of Luck.

Wednesday, April 11, 2012

Why to and How use to jQuery?

        Here I will talk about jQuery, a very useful javascipt library. I will tell you why to use jQuery and how to use jQuery.
First and very important thing about jQuery , that even you will find first on jquery.com, is that it is NOT a programming language but simply a JavaScript Library.
If you want to use it, just go to their site and download appropriate .js file. You can download either production version or Development one for you. See which one suits for you...
  •   Production Version is lesser in size, but its content is not readable so you almost can't modify it. If you don't want to modify it, use this version, as this will reduce page load time. This will have "min" it's .js file name.
  • Development version is quite larger in size and in editable format. So on other way if you want to modify this, you will go for this version.

Why to jQuery?

There are five main reasons for selecting jQuery.
  1. It is simple to use. We need to write less code and it does more(as they say).
  2. Great support from forums and easy documentation.
  3. Ajax support.
  4. jQueryUI can be used very easily to develop very good User Interface Components.
  5. Large very large actually, Number of Plugins are available, that would help you do lot more things in easy way. Plugins are available from simple ToolTip plugins to complex Image Viewer to Great Menu Structures.
And i have stated these reasons in ascending order of importance...
Plugins are very useful, you will thank them a lot when you will be in need..

How to jQuery ?

After going through why to use jQuery let's see how to use jQuery.
The basic syntax for jQuery Statement is 
 $(Selector).event();
As this is javaScript library , all jQuery lines comes under 
<Script>
</Script> tag or separate .js file.

It is always safe to write jQuery code under following function
$(document).ready(function(
{
//code here
}));
this is also jQuery statement, meaning, execute following code only after document is ready means document's DOM structure is ready.
This ready is different than onload function of javascript, ready is when whole DOM structure of HTML document is ready, and onload is when entire content, including all images on the page, is loaded in the browser.
Main purpose of jQuery is to travel through elements on the page, assign some event handlers for them and perform some action on them.


Selectors :

There are many selectors of different form,
  • Few allow you to select elements by their attributes, those of [] form.
  • Select multiple elements.
  • Select by class or id value.
  • Few of ":" type allow you to filter the set by some way like for example :first would select first element of the preselected set of elements.
  • Few playing with parent child relationships.

Events :

Events allow you to subscribe some event handles for some of the event types on some elements. Events like .click(),  .mouseover() , .focus(),  keydown() are handy.
Also there are many methods to bind particular even customized events with handlers like .bind(type , data , function), on(type,selector,data,function)  etc.



Effects :

There are many methods to apply great variety of effects to selected elements.
Ex. .css(attributes) allow you to change css properties of the elements.
.addClass(class),  .toggleClass(class)
.show()  ,  .hide(speed)
.slideDown()
.animate()
.fadeIn()  ,  .fadeOut().
and many more, and many with overloaded forms with different parameters.

Manipulation :

There are many ways you can manipulate the elements and contents of them.
Ex. .append(content) 
.after(content)
.wrap(html)
.replaceWith(content)
.empty()
.clone()

Traversing :

Few of them allow you to travel through the documents with some relations. Like for example 
.parent()    .nextAll()   .each(f)  .children() etc.

Ajax :

There is great deal of support for ajax in jQuery. At this point it's adequate to just know that it DOES support ajax with methods like.
.ajaxComplete(c)
.ajaxStart(c)
$ajax( options ) etc.


And don't forget this one jQuery Complete Cheat Sheet .