Thursday, 22 August 2013

JQuery Effects:

Showing and Hiding elements:

The commands for showing and hiding elements are pretty much what we would expect: show()to show the elements in a wrapped set and hide() to hide them.

Syntax:

Here is the simple syntax for show() method:
[selector].show( speed, [callback] );
Here is the description of all the parameters:
  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.
Following is the simple syntax for hide() method:
[selector].hide( speed, [callback] );
Here is the description of all the parameters:
  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example:

Consider the following HTML file with a small JQuery coding:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("#show").click(function () {
        $(".mydiv").show( 1000 );
     });

     $("#hide").click(function () {
        $(".mydiv").hide( 1000 );
     });

   });

   </script>
   <style>
   .mydiv{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:100px;
    }
  </style>
</head>
<body>
   <div class="mydiv">
      This is  SQUAR
   </div>

   <input id="hide" type="button" value="Hide" />   
   <input id="show" type="button" value="Show" />   

</body>
</html>
To understand it in better way you can Try it yourself.

Toggling the elements:

jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown.

Syntax:

Here is the simple syntax for one of the toggle() methods:
[selector]..toggle([speed][, callback]);
Here is the description of all the parameters:
  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example:

We can animate any element, such as a simple <div> containing an image:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $(".clickme").click(function(event){
          $(".target").toggle('slow', function(){
             $(".log").text('Transition Complete');
          });
      });

   });
   </script>
   <style>
   .clickme{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:50px;
    }
   </style>
</head>
<body>
   <div class="content">
      <div class="clickme">Click Me</div>
      <div class="target">
         <img src="/images/jquery.jpg" alt="jQuery" />
      </div>
      <div class="log"></div>
</body>
</html>
To understand it in better way you can Try it yourself.

JQuery Effect Methods:

You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects:
Methods and Description
animate( params, [duration, easing, callback] )
A function for making custom animations.
fadeIn( speed, [callback] )
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
fadeOut( speed, [callback] )
Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion.
fadeTo( speed, opacity, callback )
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
hide( )
Hides each of the set of matched elements if they are shown.
hide( speed, [callback] )
Hide all matched elements using a graceful animation and firing an optional callback after completion.
show( )
Displays each of the set of matched elements if they are hidden.
show( speed, [callback] )
Show all matched elements using a graceful animation and firing an optional callback after completion.
slideDown( speed, [callback] )
Reveal all matched elements by adjusting their height and firing an optional callback after completion.
slideToggle( speed, [callback] )
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
slideUp( speed, [callback] )
Hide all matched elements by adjusting their height and firing an optional callback after completion.
stop( [clearQueue, gotoEnd ])
Stops all the currently running animations on all the specified elements.
toggle( )
Toggle displaying each of the set of matched elements.
toggle( speed, [callback] )
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
toggle( switch )
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
jQuery.fx.off
Globally disable all animations.

UI Library Based Effects:

To use these effects you would have to download jQuery UI Library jquery-ui-1.7.2.custom.min.js or latest version of this UI library from jQuery UI Library.
After extracting jquery-ui-1.7.2.custom.min.js file from the download, you would include this file in similar way as you include core jQuery Library file.
Methods and Description
Blind
Blinds the element away or shows it by blinding it in.
Bounce
Bounces the element vertically or horizontally n-times.
Clip
Clips the element on or off, vertically or horizontally.
Drop
Drops the element away or shows it by dropping it in.
Explode
Explodes the element into multiple pieces.
Fold
Folds the element like a piece of paper.
Highlight
Highlights the background with a defined color.
Puff
Scale and fade out animations create the puff effect.
Pulsate 
Pulsates the opacity of the element multiple times.
Scale
Shrink or grow an element by a percentage factor.
Shake
Shakes the element vertically or horizontally n-times.
Size
Resize an element to a specified width and height.
Slide 
Slides the element out of the viewport.
Transfer
Transfers the outline of an element to another.

JQuery DOM Traversing Methods:


Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:
SelectorDescription
eq( index )Reduce the set of matched elements to a single element.
filter( selector )Removes all elements from the set of matched elements that do not match the specified selector(s).
filter( fn )Removes all elements from the set of matched elements that do not match the specified function.
is( selector )Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector.
map( callback )Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements).
not( selector )Removes elements matching the specified selector from the set of matched elements.
slice( start, [end] )Selects a subset of the matched elements.
Following table lists down other useful methods which you can use to locate various elements in a DOM:
SelectorDescription
add( selector )Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( )Add the previous selection to the current selection.
children( [selector])Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest( selector )Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents( )Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end( )Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state .
find( selector )Searches for descendent elements that match the specified selectors.
next( [selector] )Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll( [selector] )Find all sibling elements after the current element.
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] )Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
parents( [selector] )Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
prev( [selector] )Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll( [selector] )Find all sibling elements in front of the current element.
siblings( [selector] )Get a set of elements containing all of the unique siblings of each of the matched set of elements.

Useful Attribute Methods in JQuery:


Following table lists down few useful methods which you can use to manipulate attributes and properties:
MethodsDescription
attr( properties )Set a key/value object as properties to all matched elements.
attr( key, fn )Set a single property to a computed value, on all matched elements.
removeAttr( name )Remove an attribute from each of the matched elements.
hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class )Removes all or the specified class(es) from the set of matched elements.
toggleClass( class )Adds the specified class if it is not present, removes the specified class if it is present.
html( )Get the html contents (innerHTML) of the first matched element.
html( val )Set the html contents of every matched element.
text( )Get the combined text contents of all matched elements.
text( val )Set the text contents of all matched elements.
val( )Get the input value of the first matched element.
val( val )Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.
Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:
  • $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.
  • $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".
  • $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.
  • $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank
  • $("a").removeAttr("target") : This would remove target attribute of all the links.
  • $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.
  • $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected.
  • $("p").text(): Returns string that contains the combined text contents of all matched <p> elements.
  • $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> elements
  • $("p").html() : This returns the HTML content of the all matching paragraphs.
  • $("div").html("Hello World") : This would set the HTML content of all matching <div> to Hello World.
  • $("input:checkbox:checked").val() : Get the first value from a checked checkbox
  • $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons
  • $("button").val("Hello") : Sets the value attribute of every matched element <button>.
  • $("input").val("on") : This would check all the radio or check box button whose value is "on".
  • $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange, Mango and Banana.
  • $("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

Applying Styles in JQuery


The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>

JQuery-Selectors

  1. $('*'): This selector selects all elements in the document.
  2. $("p > *"): This selector selects all elements that are children of a paragraph element.
  3. $("#specialID"): This selector function gets the element with id="specialID".
  4. $(".specialClass"): This selector gets all the elements that have the class ofspecialClass.
  5. $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
  6. $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  7. $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.
  8. $("ul li:first"): This selector gets only the first <li> element of the <ul>.
  9. $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.
  10. $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>
  11. $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
  12. $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
  13. $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.
  14. $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class ofmyclass.
  15. $(":empty"): Selects all elements that have no children.
  16. $("p:empty"): Selects all elements matched by <p> that have no children.
  17. $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
  18. $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
  19. $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.
  20. $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.
  21. $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.
  22. $("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar
  23. $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.
  24. $("li:even"): Selects all elements matched by <li> that have an even index value.
  25. $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.
  26. $("li:first"): Selects the first <li> element.
  27. $("li:last"): Selects the last <li> element.
  28. $("li:visible"): Selects all elements matched by <li> that are visible.
  29. $("li:hidden"): Selects all elements matched by <li> that are hidden.
  30. $(":radio"): Selects all radio buttons in the form.
  31. $(":checked"): Selects all checked boxex in the form.
  32. $(":input"): Selects only form elements (input, select, textarea, button).
  33. $(":text"): Selects only text elements (input[type=text]).
  34. $("li:eq(2)"): Selects the third <li> element
  35. $("li:eq(4)"): Selects the fifth <li> element
  36. $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
  37. $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
  38. $("li:gt(1)"): Selects all elements matched by <li> after the second one.
  39. $("p:gt(2)"): Selects all elements matched by <p> after the third one.
  40. $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.
  41. $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.
  42. $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>
  43. $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.
  44. $("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.
  45. $(":parent"): Selects all elements that are the parent of another element, including text.
  46. $("li:contains(second)"): Selects all elements matched by <li> that contain the text second.

Tuesday, 20 August 2013

Properties in C# : How/Why we use this?


class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod();
        std.SetRoll(1);
        std.SetName("Abhimanyu");
        Console.WriteLine("Roll: {0} and Name: {1}", std.GetRoll(), std.GetName());
        Console.ReadKey();
    }
}

public class StudentMethod
{
    private int Roll = 1;

    public int GetRoll()
    {
        return Roll;
    }

    public void SetRoll(int r)
    {
        Roll = r;
    }

    private string Name = string.Empty;

    public string GetName()
    {
        return Name;
    }

    public void SetName(string n)
    {
        Name = n;
    }
}

The StudentMethod class has four methods, two for each private field that the class encapsulates: Roll and Name. As you can see, SetRoll and SetName assign a new values and GetRoll and GetName return values.

Observe how Main calls the SetRoll and SetName methods, which sets Roll to 1 and Name to "Abhimanyu" in the StudentMethod instance, std.  The call to Console.WriteLine demonstrates how to read Roll and Name from std, via GetRoll and GetName method calls, respectively.

This is actually real pain for developers to write such a long set of Methods. Even this is such a common pattern, that C# has embraced it in the form of a language feature called properties.

Features of Properties

There are a few reasons to use properties, instead of public fields/methods.

(i)           Properties can be virtual.
(ii)          You can make the setters for a property private.
(iii)         Properties have a 'special' meaning to things that inspect classes at runtime.

With Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod();
        std.Roll = 1;
        std.Name = "Abhimanyu";
        Console.WriteLine("Roll: {0} and Name: {1}", std.Roll, std.Name);
        Console.ReadKey();
    }
}

public class StudentMethod
{
    public int Roll { getset; }
    public string Name { getset; }
}

Notice how the get and set accessors in above example do not have implementations, it is just an auto-implemented property. In an auto-implemented property, the C# compiler creates the backing store field behind the scenes, giving the same logic that exists with traditional properties, but saving you from having to use all of the syntax of the traditional property. As you can see in the Main method, the usage of an auto-implemented property is exactly the same as traditional properties.


This was a read and write property, but you can also create read-only properties or write-only properties.

Read-Only Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod(1, "Abhimanyu");
        Console.WriteLine("Roll: {0} and Name: {1}", std.ro, std.na);
        Console.ReadKey();
    }
}

public class StudentMethod
{
    private int Roll = 1;
    private string Name = string.Empty;

    public StudentMethod(int r, string n)
    {
        Roll = r;
        Name = n;
    }

    public int ro
    {
        get
        {
            return Roll;
        }
    }

    public string na
    {
        get
        {
            return Name;
        }
    }
}

The StudentMethod class in above example has two read-only properties, Roll and Name. You can tell that each property is read-only because they only have get accessor. At some time, values for the Roll and Name must be assigned, which is the role of the constructor.

The Main method of the Student class instantiates a new StudentMathod object named std. The instantiation of std uses the constructor of StudentMethod class, which takes int and string type parameters. In this case, the values are 1 as r and "Abhimanyu" as n. This initializes the Roll and Name fields of std.

Since the Roll and Name properties of the StudentMethod class are read-only, there is no other way to set the value of the Roll and Name fields. If you inserted std.Roll = 1 into the listing, the program would not compile, because Roll is read-only; the same with Name field. When the Roll and Name properties are used in Console.WriteLine, they work fine. This is because these are read operations which only invoke the get accessor of the Roll and Name properties.

Write-Only Properties

class Student
{
    static void Main(string[] args)
    {
        StudentMethod std = new StudentMethod();
        std.ro = 1;
        std.na = "Abhimanyu";

        std.DisplayStudentMethod();

        Console.ReadKey();
    }
}

public class StudentMethod
{
    private int Roll = 1;
    private string Name = string.Empty;

    public void DisplayStudentMethod()
    {
        Console.WriteLine("Roll: {0} and Name: {1}", Roll, Name);
    }

    public int ro
    {
        set
        {
            Roll = value;
        }
    }

    public string na
    {
        set
        {
            Name = value;
        }
    }
}

This time, the get accessor is removed from the Roll and Name properties of the StudentMethod class. The set accessors have been added, assigning value to the backing store fields, Roll and Name.

The Main method of the Student class instantiates the StudentMethod class with a default constructor. Then it uses the ro and na properties of std to set the Roll and Name fields of std to 1 and "Abhimanyu", respectively. This invokes the set accessor of Roll and Name properties from the std instance.