interviews.dotnetthread.com

↑ Grab this Headline Animator

Sunday, June 7, 2009

Fundamentals of jQuery


Introduction:
. jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers.
. The jQuery framework is extensible and very nicely handles DOM manipulations, CSS, AJAX, Events and Animations.
Selector: An expression for identifying target elements on a page that allows us to easily identify and grab the elements we need.
. jQuery focuses on retrieving elements from our HTML pages and performing operations upon them.

<button
type="button"
onclick="document.getElementById('xyz').style.color='red';">
Click Me
</button>

window.onload = function() {
document.getElementById('testButton').onclick = makeItRed;
};


. Consistent across all browsers.
. Solves major javascript problems
. Easily extendable

jQuery wrapper
. To collect a group of elements, we use the simple syntax $(selector) or jQuery(selector)
. The $() function (an alias for the jQuery() function) returns a special Java-Script object containing an array of the DOM elements that match the selector.
. This object possesses a large number of useful predefined methods that can acton the group of elements.
. This type of construct is termed a wrapper because it wraps the matching element(s) with extended functionality. $("div.notLongForThisWorld").fadeOut();
. A special feature of a large number of these methods, which we often refer to as jQuery commands, is that when they’re done with their action (like a fading-out operation), they return the same group of elements, ready for another action. $("div.notLongForThisWorld").fadeOut().addClass("removed");

. Along with selectors that we already know jQuery supports all selectors in CSS and also custom selectors
Here are a few examples.

$("p:even"); - This selector selects all even <p> elements.
$("tr:nth-child(1)"); - This selector selects the first row of each table.
$("body > div"); - This selector selects direct <div> children of <body>.
$("a[href$=pdf]"); - This selector selects links to PDF files.
$("body > div:has(a)") - This selector selects direct <div> children of <body>-containing links. http://docs.jquery.com/Selectors

Utility functions

. jQuery’s $() function – along with wrapping elements to be operated upon it serves as a namespace prefix for a handful of general purpose Utility functions.
. Notation: $.trim(someString); / jQuery.trim(someString);


The document ready handler
. Unobtrusive JavaScript - behavior is separated from structure
We willll be performing operations on the page elements outside of the document markup that creates them. In order to achieve this, we need a way to wait until the DOM elements of the page are fully loaded before those operations execute.
. In the zebra-striping example, the entire table must load before striping can be applied.
window.onload = function() {
$("table tr:nth-child(even)").addClass("even");
};
. The onload handler for the window instance is used for this purpose, executing statements after the entire page is fully loaded.
. Browser will delay calling onload till DOM tree is created and all images/other external
resources are fully loaded.
. Better approach would be to wait till DOM tree is ready and before executing scripts to apply rich behavior. jQuery provides a simple means to trigger the execution of code once the DOM tree, but not external image resources, has loaded.
$(document).ready(function() {
$("table tr:nth-child(even)").addClass("even");
});
. We can use this technique multiple times within the same HTML document


Extending jQuery

. jQuery is designed to be easily extended with additional functionality.
. jQuery makes it easy to extend its set of functions by extending the wrapper returned when we call $().

$.fn.disable = function()
{
return this.each
(
function()
{
if (typeof this.disabled != "undefined") this.disabled = true;
}
);
}

. Our brand new disable() method will support chaining like many of the native jQuery methods. We’ll be able to write
$("form#myForm input.special").disable().addClass("moreSpecial");

. Moreover, enterprising jQuery users have extended jQuery with sets of useful
functions that are known as plugins.

Selecting and Manipulating elements

Selectors Lab: http://www.aacr9.com/jquery/jQueryInAction/jqia.source/chapter2/lab.selectors.html http://www.codylindley.com/jqueryselectors/
. Using the basic CSS selectors like
■ a—This selector matches all link (<a>) elements.
■ #specialID—This selector matches elements that have an id of specialID.
■ .specialClass—This selector matches elements that have the class of specialClass.
■ a#specialID.specialClass—This selector matches links with an id of specialID and a class of specialClass.
■ p a.specialClass—This selector matches links with a class of specialClass declared within <p> elements.

. To select elements using jQuery, we wrap the selector in $() Ex: $("p a.specialClass")
. With a few exceptions , jQuery is fully CSS3 compliant.
. jQuery doesn’t depend upon the CSS implementation of the browser it’s running within. Even if the browser doesn’t implement a standard CSS selector correctly, jQuery will correctly select elements according to the rules of the World Wide Web Consortium (W3C) standard.
. Using child, container, and attribute selectors

. Only a single level of nesting is supported. Although it’s possible to nest one level , such as foo:not(bar:has(baz)) , li:not(:has(a)) additional levels of nesting, such as foo:not(bar:has(baz:eq(2))) aren’t supported.
Selecting by position:
. Sometimes, we’ll need to select elements by their position on the page or in relation to other elements. We might want to select the first link on the page, or every other paragraph, or the last list item of each list.
. For more advanced selectors, jQuery uses the next generation of CSS supported by Mozilla Firefox, Internet Explorer 7, Safari, and other modern browsers.
. These advanced selectors include selecting the direct children of some elements, elements that occur after other elements in the DOM, and elements with attributes matching certain conditions.

. Only a single level of nesting is supported. Although it’s possible to nest one level , such as foo:not(bar:has(baz)) , li:not(:has(a)) additional levels of nesting, such as foo:not(bar:has(baz:eq(2))) aren’t supported.
Selecting by position:
. Sometimes, we’ll need to select elements by their position on the page or in relation to other elements. We might want to select the first link on the page, or every other paragraph, or the last list item of each list.


. The nth-child selector starts counting from 1, whereas the other selectors start counting from 0.
. :eq (absolute position selector) is 0-based, but :nth-child is 1-based.



. Ex: To select only enabled checked checkboxes :checkbox:checked:enabled

. Using the :not filter – To inverse all these filters To select non-check box <input> elements, we use
input:not(:checkbox)
. We can apply the :not filter to filter selectors, but not to find selectors. The
Selector div p:not(:hidden) is a perfectly valid selector, but div :not(p:hidden) isn’t.
. Along with all these selectors we have a plugin “Basic Xpath”. This plugin adds in basic XPath selector functionality
. Plug-in supports /, //, *,[@p=value],[@p], position()
$("<div>Hello</div>")
. This expression creates a new <div> element ready to be added to the page
. We can run any jQuery commands that we could run on wrapped element sets of existing elements on the newly created fragment.
. $("<div class=‘test'>I have foo!</div><div>I don't</div>").filter(".test").click(function() {
alert("I'm foo!");}).end().appendTo("#someParentDiv");
. We can get a lot accomplished without writing a lot of script.

. Determining the size of the wrapped set $('a').size()
. Obtaining elements from the wrapped set jQuery allows us to treat the wrapped set as a JavaScript array, we can use simple array indexing to obtain any element in the wrapped list by position. $('img[alt]')[0] or $('img[alt]').get(0) Ex: var allLabeledButtons = $('label+button').get();
. Adding more elements to the wrapped set Let’s say that we want to match all elements that have either an alt or a title attribute. $('img[alt],img[title]') or $('img[alt]').add('img[title]') $('img[alt]').add(someElement) $('p').add('<div>Hi there!</div>')
. $('img[alt]').addClass('thickBorder').add('img[title]‘).addClass('seeThrough')
not() method to remove elements from the wrapped set anywhere within a jQuery chain of commands - $('img[title]').not('[title*=puppy]')
the selectors we can pass to the not() method are limited to filter
. Expressions that omit any element reference (allowing it to imply all element types).

. In case we want to filter the wrapped set in ways that are difficult or impossible to express with a selector expression. Instead of iterating through all the elements we can use jQuery’s filter()
. The filter() method, when passed a function, invokes that function for each wrapped element and removes any element whose function invocation returns the value false.
. Each invocation has access to the current wrapped element via the function context (this) in the body of the filtering function. Any element that returns an invocation of false is removed from the set.
Ex : $('td').filter(function(){return this.innerHTML.match(/^\d+$/)})
. The filter() method can also be used with a passed selector expression that conforms to the same constraints that we described earlier for the not() method, namely, filter selectors with an implied element type.
$('img').addClass('seeThrough').filter('[title*=dog]‘).addClass('thickBorder')
. Subsets of the wrapped set To obtain a subset of the wrapped set, based on the position of elements within the set.
. slice(begin,end)
. To grab elements from the end of the wrapped set, the statement - $('*').slice(4);
. Getting wrapped sets using relationships These methods give us a large degree of freedom to select elements from the DOM, based on relationships to the other DOM elements.

. The find() method lets us search through an existing wrapped set and returns a new set that contains all elements that match a passed selector expression. - wrappedSet.find('p cite')
. jQuery also provides a method to find elements that contain a specified string. - $('p').contains('Lorem ipsum')
. The is() method returns true if at least one element matches the selector, and false if not . - is(selector)
. The easiest way to inspect or modify the component elements of a matched set is with the each() command.
Ex: $('img').each(function(n)
{
this.alt='This is image['+n+'] with an id of '+this.id;
});
. To collect all values for a specific property into an array using each(), as follows:
var allAlts = new Array();
$('img').each(function(){
allAlts.push(this.alt);
});
. var altValue = $('#myImage')[0].alt;
. attr(name) - To obtain the values assigned to the specified attribute for the first element in the matched set. - $("#myImage").attr("custom")
. Setting attribute values: attr(name,value)
. Setting multiple attributes at a time: attr(attributes) Ex: $('input').attr({ value: '', title: 'Please enter a value' });
. Removing Attributes: removeAttr(name)
. jQuery attr() normalized-access names

.Changing Element Styling:
addClass(names)
removeClass(names)
toggleClass(name)
css(name,value) – Applying Styles directly onto the elements
css(properties)
css(name)

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles