Tuesday 15 December 2009

Manipulating Page Content using jQuery

Hi,

In this blog we will learn how to manipulate the page contents using jQuery.
The topics we will learn in today's blog are:
  • Overview of content manipulation:
  • Creating, setting, and getting content
  • Manipulating attributes
  • Inserting Content
  • Wrapping, replacing, removing content
  • Working with CSS information
  • Working with CSS classes
  • Working with CSS positioning
  • Working with CSS sizing information

    Overview of content manipulation:
    • Once you’ve used selectors and filters to retrieve web page content, you usually want to do something with it
    • Sometimes you want to create new content to dynamically add into the page
    • jQuery has functions for creating, copying, deleting, and moving content around, as well as wrapping page content in other content
    • jQuery provides cross-browser support for working with CSS, including positioning and sizing information
    Creating, setting, and getting content:
    • To create new HTML content, you simply pass a string containing new HTML to the $() function:
    Var newHeader = $(“My new header”);
    Var myStr = “My new header”;
    Var newHeader = $(myStr);
    • In addition to this method, you can use the html() and text() methods to get and set content on
    Function
    Purpose
    html()
    Returns the HTML content of the first matched element
    html(newcontent)
    Sets the HTML content of every matched element
    text()
    Returns the text content of the first matched element
    text(newtext)
    Sets the text content for all matched elements
    Manipulating attributes:
    • To inspect or change the value of attribute on elements, use jQuery’s  attr functions
    Function
    Purpose
    attr(name)
    Accesses property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned
    attr(properties)
    Set a series of attributes on all matched element using an object notation syntax. This is the best used for setting large numbers of properties at once
    $(“img”).attr({ src: “/images/hat.gif”, title: “jQuery”, alt: “jQuery Logo”});
    attr(key, value)
    Sets a single property to a value on all matched elements
    attr(key, fn)
    Sets a single property to a computed value, on all matched elements. Instead of supplying a string value, a function is provided that computes the value of the attribute
    removeAttr(name)
    Removes the named attribute from all matched elements
    Inserting Content:
    • JQuery provides several functions for inserting content into the document, both before and after existing page elements
    Function
    Purpose
    append(content)
    Appends content to the inside of every matched element
    appendTo(selector)
    Appends all of the matched elements to another, specified, set of elements
    prepend(content)
    Prepends content to the inside of every matched element
    prependTo(selector)
    Prepends all the matched elements to another, specified, set of elements
    after(content)
    Inserts content after each of the matched elements
    before(content)
    Inserts content before each of the matched elements
    insertAfter(selector)
    Inserts all of the matched elements after another, specified, set of elements
    insertBefore(selector)
    Inserts all of the matched elements before another, specified, set of elements
    Wrapping, replacing, removing content:
    • jQuery can wrap existing content in the page, replace content, copy content, and remove it
    Function
    Purpose
    wrap(html)
    Wraps each matched element with the specified HTML content
    wrap(element)
    Wraps each matched element with the specified element
    wrapAll(html)
    Wraps all the elements in the matched set with the specified HTML content
    wrapAll(element)
    Wraps all the elements in the matched set into a single wrapper element
    wrapInner(html)
    Wraps the inner child contents of each matched element (including text nodes) with an HTML structure
    wrapInner(element)
    Wraps the inner child contents of each matched element (including text nodes) with a DOM structure
    replaceWith(content)
    Replaces all matched elements with the specified HTML or DOM elements
    replaceAll(selector)
    Replaces the elements matched by the specified selector with the matched elements
    empty()
    Removes all child nodes from the set of matched elements
    remove()
    Removes all matched elements from the DOM
    clone()
    Clone matched DOM elements and selects the clones
    clone(bool)
    Clone matched DOM elements, and all their event handlers, and select the clones
    Working with CSS information:
    • jQuery’s CSS functions provide easy, cross-browser access for setting properties and working with positioning and sizing information
    • The css() function allows you to retrieve and set CSS styles for a set of matched elements
    Filter
    Purpose
    css(name)
    Returns the value for the named CSS property for the first matched element
    css(properties)
    Sets the CSS properties of every matched element using an object-notation syntax:
    var cssObj = {
    ‘background-color’  :  ‘#ddd’,
    ‘font-weight’ : ‘ ‘
    ‘color’ : ‘rgb(0, 40, 244)’ }
    $(this).css(cssObj);
    css(property, value)
    Sets a single style property to a value on all matched elements. If a number is provided, it is automatically converted into a pixel value, with the following exception: z-index, font-weight, opacity, zoom, and line-height
    Working with CSS classes:
    • jQuery provides a set of functions for working with CSS classes on page elements
    • Classes can be easily added, removed, toggled, and detected
    CSS Functions
    Purpose
    addClass(class)
    Adds the specified class(es) to each of 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 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
    toggleClass(class, switch)
    Adds the specified class if the switch is true, removed the specified class if the switch is false
    Working with CSS positioning:
    • The CSS positioning functions provide cross-browser support for figuring out the positions of elements
    CSS Functions
    Purpose
    offset()
    Gets the current offset of the first matched element, in pixels, relative to  the document
    offsetParent()
    Returns a jQuery collection with the positioned parent of the first matched element
    position()
    Gets the top and left position of an element relative to its offset parent
    scrollTop()
    Gets the scroll top offset of the first matched element
    scrollTop(val)
    Sets the scroll top offset to the given value on all matched elements
    scrollLeft()
    Gets the scroll left offset of the first matched element
    scrollLeft(val)
    Sets the scroll left offset to the given value on all matched elements
    Working with CSS sizing information:
    • To retrieve cross-browser sizing information for elements, use the jQuery size-related CSS function
    CSS Functions
    Purpose
    height()
    Gets the current computed, pixel, height of the first matched element
    height(val)
    Sets the CSS height of every matched element
    width()
    Gets the current computed, pixel, width of the first matched element
    width(val)
    Sets the CSS width of every matched element
    innerHeight()
    Gets the inner height (excluding the border and including the padding) for the first matched element
    innerWidth()
    Gets the inner width (excluding the border and including the padding) for the first matched element
    outerHeight(margin)
    Gets the outer height (includes the border and padding by default) for the first matched element. If the margin argument is true, then the margin values are also included
    outerwidth(margin)
    Gets the outer width (includes the border and padding by default) for the first matched element. If the margin argument is true, then the margin values are also included
    In the next blog we will learn Working with events using jQuery.

jQuery Selectors and Filters


Hi,
Welcome back.
In the last blog you saw the jQuery overview.
In this blog we will learn:

  • Overview of Selectors and Filters
  • Using basic jQuery selectors
  • Using filters
  • Using basic jQuery filters
  • Attribute filters
  • Content and Visibility filters
  • Child filters
  • Form selectors
  • Traversing Document Information
  • jQuery  statement chaining


Overview of Selectors and Filters:
  • jQuery selectors and filters retrieve contents from the documents so it can be manipulated using other functions
-          jQuery selectors return an array of objects that match the selection criteria
-          jQuery filters operates on a selectors to further refine the results array that the selector returns
  • This array is not a set of DOM elements
  • It is a collection of jQuery objects that provide a large number of predefined functions for further operating on the objects
Using basic jQuery selectors
  • CSS-style selectors and filters are based on familiar CSS syntax, and work pretty much the same way as CSS does
  • The CSS selectors listed here correspond directly to their CSS counterpart s
Selectors
Purpose
tagname
Finds all elements that are named tagname
#identifier
Finds all elements with ID of identifier
.className
Finds all elements that have class attribute with the value of className
tag.className
Get elements of type tag that have a class attribute with the value of className
tag#id.className
Retrieves the tag element that has an ID of id and a class attribute with the value of className
*
Finds all of the elements on the page
  • The hierarchy and combination selectors allow you to get a little more advanced in selecting page content
  • You can select elements based on hierarchical relationships or on a series of comman criteria
Selector
Purpose
selector, selector
Finds all of the specified selectors
.class1.class2
Finds all elements with both .class1 and .class2 applied
Parent>child
Finds all child elements that are direct children of elements of type parent
Ancestor descendant
Finds all descendant elements that are contained within elements of type ancestor
Prev + next
Finds all next elements that are next to prev element
Prev ~ siblings
Finds all sibling elements that come after prev and match the siblings selector

Using filters
  • Filters work with selectors to provide even more fine-grained control over how elements are selected in the document
  • jQuery filters fall into six different categories
  1. Basic: Provides basic filtering, like getting the first, last, and even- and odd-numbered items in a returned set
  2. Content: Filters a set of elements based on the content, like whether an element contains a particular string
  3. Visibility: Filters a set of elements using the visibility setting of each element as a test
  4. Attribute: Examines a given attribute on an element to determine whether it should be filtered out
  5. Child: Selects elements based upon their relationship with their parent element
  6. Form: Provides specialized filters that operate on form elements
Using basic jQuery filters:
  • You can refine a selector by including elements that match certain conditions, like position or index
Filter
Purpose
:first
Selects only the first instance of the selector’s returned set
:last
Selects only the last instance of the selector’s returned set
:even
Selects only even-numbered elements in the selector’s returned set
:odd
Selects only odd-numbered elements in the selector’s returned set
:eq(n)
Filters out elements that are not positioned at the given index
:gt(n)
Includes elements that are past the given index
:lt(n)
Includes elements that are before the given index
:header
Selects all header elements (H1, H2, H3, etc)
:animated
Selects all elements that are currently being animated in some way
:not(selector)
Includes elements that do not match the given selector

Attribute filters:

  • You can filter the results of a selector statement based on attribute content
Filter
Purpose
[attribute]
Includes elements in the result set if they have the specified attribute
[attribute=value]
Includes elements in the result set if they have the specified attribute and it has the given value
[attribute!=value]
Includes elements in the result set only if they have the specified attribute and it doesn’t have the given value
[attribute^=value]
Includes elements that have the specified attribute and it starts with the specified value
[attribute$=value]
Includes elements that have the specified attribute and it ends with the specified value
[attribute*=value]
Includes elements that have the specified attribute and it contains the specified value
[attrFilter1][attrFilterN]
Includes elements that match all of the specified attribute filters

 Content and Visibility filters:
  • You can examine the content of selected elements or their visibility property to determine whether they should be included or excluded from the final set
Content filter
Purpose
:contains(text)
Filters the selection to only include elements that contain the text string
:empty
Filters the selection to only include empty elements
:has(selector)
Matches elements that contain at least one element that has the specified selector
:parent
Matches all elements that are parents (i.e. they contain at least one other element, including text)

Visibility filter
Purpose
:visible
Filters the selection to only include visible elements
:hidden
Filters the selection to only include hidden elements

Child filters:
  • You can refine a selector by examining the relationship each element has with its parent element
Filter
Purpose
:nth-child(index)
:nth-child(even)
:nth-child(odd)
:nth-child(equation)
Matches elements at index, or even or odd increments, or who match an equation of the form Xn+M (e.g., 2n or 3n+1)
:first-child
Matches elements who are the first child of their parent
:last-child
Matches elements who are the last child of their parent
:only-child
Matches elements who are the only child of their parent

Form selectors:

  • You can use form selectors to deal with form elements
  • They work like other selectors but start with a colon (:) like a regular filter
Selector
Purpose
:input
Finds all input, select, textarea, and button elements
:text
Finds all text elements
:password
Finds all password elements
:radio
Finds all radio button elements
:checkbox
Finds all checkbox elements
:submit
Finds all submit elements
:reset
Finds all reset elements
:image
Finds all image elements
:button
Finds all button elements
:file
Finds all file upload elements
  • You can perform additional filtering of form elements, such as whether items are checked, selected, or enabled
Selector
Purpose
:enabled
Matches all form elements that are enabled
:disabled
Matches all form elements that are disabled
:checked
Matches all form elements that are checked (radiobuttons and checkboxes)
:selected
Matches all form elements that are selected

Traversing Document Information:
  • You can traverse the information returned from a document easily
Function / Property
Purpose
Size(), length
The number of elements in the jQuery result set
get()
Returns an array of all matched DOM elements. Useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions
get(index)
Access a single matched DOM element at a specified index in the matched set
find(expression)
Searched for descendent elements that match the specified expression
each(fn)
Execute a function within the context of every matched element

jQuery  statement chaining:
  • One of jQuery’s most powerful features is its ability to chain multiple functions together to perform several operations in one line of code
$(selector).fn1().fn2().fn3();
                     statement chain
In the next blog we will learn how to manipulate the page contents using jQuery.



Sunday 13 December 2009

jQuery Overview

Hi Welcome to my blog!


This is my first blog on jQuery. 
 In this blog we will learn the following topics:
  • What is jQuery
  • Benefits of using jQuery
  • jQuery browser compatibility
  • Downloading and Installing jQuery, and
  • Creating a sample your first jQuery enabled page
  • jQuery features

1. What is jQuery
  • It is a free, open Javascript library
  • It simplifies the task of creating highly responsive web pages
  • It works across all modern browsers (list of browsers are listed in this blog later)
  • It abstracts away browser-specific features, allowing you to concentrate on design
  • It focuses on simplifying common scripting tasks like
             - Getting and manipulating page contents
             - Working with the modern browser event model
             - Adding sophisticated effects
  • Most modern web development scenarios involve common patterns like
            - page loads where you perform a bunch of page setup, and
            - event where you retrieve content from the page, manipulate 
              or animate the content, and put the  content back in the page
  • jQuery make these scenarios easy

2. Benefits of using jQuery

  • Leverages your existing knowledge of CSS (Cascading Style Sheet)
  • Works with sets of elements
  • Performs multiple operations on a set of elements with one line of code (known as statement chaining)
  • Hides various browser quirks (so you can concentrate on the end result)
  • Is extensible (so you can use third-party-plug-ins to perform specialized tasks, or write your own)

3. jQuery browser compatibility

  • jQuery currently compatible with all modern browsers in use today
Browser                         With with                          Known issues with
Internet Explorer             6.0 and greater                 1.0 through 5.x
Safari                            3 and greater                    1.0 through 2.1
Chrome                         1 and greater                     N/A
Firefox                           2 and greater                    1.0.x
Opera                            9 and greater                    1.0 through 8.x


4. Downloading and Installing jQuery
  • You can download the jQuery from http://jquery.com/  
  • jQuery comes in two versions: production (which is compressed and minified) and development
  • Typically, you download both versions and then use each one for its intended purpose

5. Creating a first simple jQuery enabled page
  • typically, code that you want to execute when the page is loaded is written like this:
       
         function RunOnLoad( ) {
              alert("Page loaded!");
    }
         window.onload = RunOnLoad;
  •  The on-load event only fires after all of the page content has downloaded, including images
  • It's also harder to add multiple load functions
  • jQuery provides a way to run code when the DOM of the page is ready. This is called the document.ready event
  • The document.ready event is written like this:
           $("document").ready( function ( ) {
                  alert("Page just loaded!");

     });
  • This code will now executed when the DOM has loaded, instead of waiting for all of the page content finish downloading
  • also, you can call document.ready funtion multiple times, and jQuery will chain together each one to be called in succession


6. jQuery features:
The features break down across eight major categories:
  1. Core Functionality: Implements core jQuery functions as well as commonly used utilities
  1. Selection and Traversal: Provides functions for finding content in documents and navigating among the contents of the document
  1. Manipulation and CSS: Provides functions for editing and changing documents content and working with CSS data such as positioning info
  1. Events: Simplifies working with the modern DOM events and provides common event helper functions
  1. Effects: Provides functions for creating basic animations and effects, such as hiding and showing elements and moving objects around
  1. Ajax: Provides utilities for working with Ajax, such as loading content from pages and dealing with JSON data
  1. User Interface: Provides an official plug-in with commonly used interface widgets, like slider controls, progress bars, accordions, etc
  1. Extensibility: Enables the construction of jQuery plug-ins that enhance the functionality of the base library
We will explore each of these functionality in details in my coming blogs.
So keep watching my blogs.