CC

 

            function readyFn() {                   

            }                                   
                         

            $(document).ready(readyFn);           

 

 

Selectors

$("p.intro")

$("*")   All
elements       

$("p")   All
p elements    

.class.class       $(".intro.demo")           All elements with the classes
"intro" and "demo"           

s1,s2,s3            $("th,td,.intro")            All elements with matching selectors     

 

Pseudo Selectors

:first     $("p:first")       The first p element         

:last      $("p:last")        The last p element          

:even    $("tr:even")      All even tr elements       

:odd     $("tr:odd")       All odd tr elements        

:eq(index)        $("ul
li:eq(3)") The fourth element in a
list (index starts at 0)    

:gt(no)  $("ul
li:gt(3)")  List elements with an
index greater than 3         

:lt(no)   $("ul
li:lt(3)")   List elements with an
index less than 3              

:not(selector)    $("input:not(:empty)") All input elements that are not empty                             

:header $(":header")     All header elements h1, h2 …    

:animated         $(":animated") All animated elements   

:contains(text)  $(":contains(‘W3Schools’)")     All elements which contains the text      

:empty $(":empty")      All elements with no child (elements)
nodes      

:hidden            $("p:hidden")   All hidden p elements    

:visible $("table:visible")          All visible tables            

:input   $(":input")        All input elements          

:text     $(":text")          All input elements with
type="text"       

:password        $(":password") All input elements with
type="password"          

:radio   $(":radio")        All input elements with
type="radio"     

:checkbox        $(":checkbox")            All input elements with
type="checkbox"          

:submit $(":submit")     All input elements with
type="submit"   

:reset    $(":reset")        All input elements with
type="reset"      

:button $(":button")      All input elements with
type="button"   

:image  $(":image")      All input elements with
type="image"    

:file      $(":file")          All input elements with
type="file"        

:enabled           $(":enabled")   All enabled input elements        

:disabled          $(":disabled")   All disabled input elements        

:selected           $(":selected")   All selected input elements        

:checked          $(":checked")   All checked input elements     

 

Attribute Selectors

 [attribute]        $("[href]")        All elements with a href attribute           

 $("[href=’default.htm’]")         All elements with attribute value equal
to "default.htm"            

 $("[href!=’default.htm’]") All
elements with a href attribute value not equal to

$("[href$=’.jpg’]")        All elements with a href attribute value ending with
".jpg"        

$("[href^=’jquery_’]")  All elements with a href attribute value starting with
"jquery_"             

 

Refining & Filtering
Selections

Sometimes you have a selection that contains more than
what you’re after; in this case, you may want to refine your selection. jQuery
offers several methods for zeroing in on exactly what you’re after.

 1         $(‘div.foo’).has(‘p’);         
// div.foo elements that contain <p>’s                         

2          $(‘h1’).not(‘.bar’);           
// h1 elements that don’t have a class of bar  

3          $(‘ul
li’).filter(‘.current’);  // unordered list items with class of current    

4          $(‘ul
li’).first();            
// just the first unordered list item                      

5          $(‘ul li’).eq(5);              
// the sixth      

 

Chaining

If you change your selection in the midst of a chain,
jQuery provides the $.fn.end method to get you back to your original selection.

 

1          $(‘#content’)
                   

2              .find(‘h3’)
       

3              .eq(2)
                         

4                  .html(‘new
text for the third h3!’)              

 

5              .end()
// restores the selection to all h3’s in #content               

6              .eq(0)
         

7                  .html(‘new
text for the first h3!’);

 

//////

 $(‘div.myClass’);
// performance improves if you specify element type          

$(‘input[name=first_name]’); // beware, this can be very
slow

 

When you use the :visible and :hidden pseudo-selectors,
jQuery tests the actual visibility of the element, not its CSS visibility or
display — that is, it looks to see if the element’s physical height and width
on the page are both greater than zero. However, this test doesn’t work with
<tr> elements; in this case, jQuery does check the CSS display property,
and considers an element hidden if its display property is set to none.
Elements that have not been added to the DOM will always be considered hidden, even
if the CSS that would affect them would render them visible. (See the
Manipulation section later in this chapter to learn how to create and add
elements to the DOM.)

 

///////////////////////////////////////////////////

TYPES OF JQUERY SELECTORS

There are three categories of jQuery selectors: Basic CSS
selectors, Positional selectors, and Custom jQuery selectors.

 

The Basic Selectors are known as "find
selectors" as they are used to find elements within the DOM. The
Positional and Custom Selectors are "filter selectors" as they filter
a set of elements (which defaults to the entire set of elements in the DOM).

 

Basic CSS Selectors

These selectors follow standard CSS3 syntax and semantics.

 

Syntax Description

*          Matches
any element.

E          Matches
all elements with tag name E.

E F       Matches
all elements with tag name F that are descendants of E.

E>F      Matches
all elements with tag name F that are direct children of E.

E+F      Matches all
elements with tag name F that are immediately preceded by a sibling of tag name
E.

E~F      Matches all
elements with tag name F that are preceded by any sibling of tag name E.

E:has(F)           Matches
all elements with tag name E that have at least one descendant with tag name F.

E.c       Matches
all elements E that possess a class name of c. Omitting E is identical to *.c.

E#i       Matches
all elements E that possess an id value of i. Omitting E is identical to *#i.

E[a]      Matches
all elements E that posses an attribute a of any value.

E[a=v]  Matches all
elements E that posses an attribute a whose value is exactly v.

E[a^=v]            Matches
all elements E that posses an attribute a whose value starts with v.

E[a$=v]            Matches
all elements E that posses an attribute a whose value ends with v.

E[a*=v]            Matches
all elements E that posses an attribute a whose value contains v.

Examples

 

$("div~p") selects all <div> elements
that are preceded by a <p> element

$("p:has(b)") selects all <p> elements
that contain a <b> element

$("img[alt]") selects all <img> elements
that possess an alt attribute

$("a[href$=.pdf]") selects all <a>
elements that possess an href attribute that ends in .pdf

$("button[id*=test]") selects all buttons whose
id attributes contain test

 

You can create the union of multiple disparate selectors
by listing them, separated by commas, in a single call to $(). For example, the
following matches all <div> and <p> elements:

 

$("div,p")

While the following, matches all <div> elements
with a title attribute, and all <img> elements with alt attributes:

 

$("div[title],img[alt]")

Positional Selectors

 

These selectors match based upon positional relationships
between elements. These selectors can be appended to any base selector (which
we"ll denote by B) to filter the matches based upon position. If B is
omitted, it is assumed to be * (the pool of all elements).

 

Syntax Description

B:first  Selects the
first element on the page matching the base selector B.

B:last   Selects the
last element on the page matching the base selector B.

B:first-child     Selects
all elements from B that are first children.

B:last-child      Selects
all elements from B that are last children.

B:only-child     Selects
all elements from B that are only children.

B:nth-child(n)  Selects
all elements from B that are n-th ordinal children. Starts at 1.

B:nth-child(odd|even)  Selects
all elements from B that are even or odd ordinal children. The first child is
considered odd (ordinal 1).

B:nth-child(Xn+Y)       Selects
all elements from B that match the formula. X denotes an ordinal multiplier,
while Y denotes an offset. Y may be omitted if 0. See the following examples.

B:even Selects the
even elements within the set of elements defined by B.

B:odd   Selects the
odd elements within the set of elements defined by B.

B:eq(n)            Selects
the n-th element within the set of elements defined by B. Starts at 0.

B:gt(n) Selects
elements within the set of elements defined by B that follow the n-th element
(exclusive). Starts at 0.

B:lt(n)  Selects
elements within the set of elements defined by B that precede the n-th element
(exclusive). Starts at 0.

Examples

 

$("p:first") selects the first

element on the page

 

$("img[src$=.png]:first") selects the first
<img> element on the page that has a src attribute ending in .png

$("li:first-child") selects all <li>
elements that are first children within their lists

$("a:only-child") selects all <a>
elements that are the only element within their parent

$("li:nth-child(2)") selects all <li>
elements that are the second item within their lists

$("tr:nth-child(odd)") selects all odd
<tr> elements within a table

$("div:nth-child(5n)") selects every 5th
<div> element

$("div:nth-child(5n+1)") selects the element
after every 5th <div> element

$(".someClass:eq(1)") selects the second element
with a class name of someClass

$(".someClass:gt(1)") selects all but the first
two elements with a class name of someClass

$(".someClass:lt(4)") selects the first four
elements with a class name of someClass

 

Note that the :nth-child selectors begin counting at 1,
while the :eq, :gt and :lt selectors begin with 0.

 

jQuery Custom Selectors

 

These selectors are provided by jQuery to allow for
commonly used, or just plain handy, selections that were not anticipated by the
CSS Specification. Like the Positional Selectors, these selectors filter a base
matching set (which we denote with B). Omitting B is interpreted as the set of
all elements. These selectors may be combined; see the examples for some
powerful selector combinations.

 

Syntax Description

B:animated      Selects
elements from the base set B that are currently under animated control via one
of the jQuery animation methods.

B:button           Selects
elements of B that are of any button type; that is: button, input[type=submit],
input[type=reset] or input[type=button].

B:input            Selects
form input elements from B; that is, <input>, <select>,
<textarea> and <button> elements.

B:not(f)            Selects
elements of B that do not match the filter selector specified by f. A filter
selector is any selector beginning with : (colon), A base set B cannot be
specified as part of f.

 of type
input[type=reset] or button[type=reset].

B:selected        Selects
elements of B that are in selected state. Only <option> elements posses
this state.

$("img:animated") selects all <img>
elements that are undergoing animation

$(":button:hidden") selects all button type
elements that are hidden

$("input[name=myRadioGroup]:radio:checked")
selects all radio elements with the name attribute value of myRadioGroup that
are checked

$(":text:disabled") selects all text fields
that are disabled

$("option:not(:selected)") selects all
unselected <option> elements

$("#myForm button:not(.someClass)") selects all
buttons from the <form> with the id of myForm that do not possess the
class name someClass.

$("select[name=choices] :selected") selects the
selected <option> elements within the <select> element named
choices.

$("p:contains(coffee)") selects all <p>
elements that contain the text coffee

Used either separately, or in combination, the jQuery
selectors give you a great deal of power to easily create a set of elements
that you wish to operate upon with the jQuery methods.

jQuery Effects

 

Here are some examples of effect functions in jQuery: 

 

Function          Description        

$(selector).hide()         Hide
selected elements              

$(selector).show()        Show
selected elements             

$(selector).toggle()       Toggle
(between hide and show) selected elements       

$(selector).slideDown()           Slide-down
(show) selected elements    

$(selector).slideUp()    Slide-up
(hide) selected elements           

$(selector).slideToggle()          Toggle
slide-up and slide-down of selected elements    

$(selector).fadeIn()      Fade
in selected elements          

$(selector).fadeOut()   Fade
out selected elements        

$(selector).fadeTo()     Fade
out selected elements to a given opacity    

$(selector).animate()    Run
a custom animation on selected elements

$(‘#div’).hide();

$(‘#div’).show();

$(‘#div’).fadeIn();

$(‘#div’).fadeOut();

 

Or you can use lots of effects like Blind, Bounce, Clip,
Drop, Explode, Fold, Highligh, Puff, Pulsate, Scale, Shake, Size, Slide,
Transfer. These are inbuilt effects available with JQuery. Not necessary to use
any plug-ins.

 

To use this effects

 

$(‘#div’)effect( effect, [options], [speed], [callback]);

Manipulating Html

 

Changing HTML Content

 

$(selector).html(content)

The html() method changes the contents (innerHTML) of
matching HTML elements.

 

Adding HTML content

 

$(selector).append(content)

The append() method appends content to the inside of
matching HTML elements.

 

$(selector).prepend(content)

The prepend() method "prepends" content to the
inside of  matching HTML elements.

 

$(selector).after(content)

The after() method inserts HTML content after all matching
elements.

 

$(selector).before(content)

The before() method inserts HTML content before all
matching elements.

·           css({properties})
– Set multiple CSS properties and values

Remove & Empty

Try this example

<a href="javascript:void(0);"
onclick="$(‘#divTestArea1’).empty();">empty() div</a>   

$(‘#divTestArea1’).remove();

The first link will call the empty() method on our test
div, removing all the child elements. The second link will remove the entire
div, including any child elements. Pretty simple stuff.

 

The remove() method comes with one optional parameter,
which allows you to filter the elements to be removed, using any of the jQuery
selector syntaxes. You could of course achieve the same simply by doing the
filtering in your first selector, but in some situations, you may be working on
a set of already selected elements. Check out this example of it in use:

Try this example

$(‘#divTestArea2 b’).remove(‘.more’);

 

Manipulating CSS

 

CSS Properties Description        

$(selector).css(name)   Get
the style property value of the first matched element          

$(selector).css(name,value)     Set the value of one style property for matched elements          

$(selector).css({properties})    Set multiple style properties for matched elements        

$(selector).height(value)          Set
the height of matched elements        

$(selector).width(value)           Set
the width of matched elements     

 

 var _height=$(‘.contentArea’).innerHeight();

 $(‘.leftCol’).css(‘height’,_height);

 $(‘.rightCol’).css(‘height’,_height);

 

Set Multiple CSS Property/Value Pairs

Use css({properties}) to set one or more CSS property/value
pairs for the selected elements:

Example

$("p").css({"background-color":"yellow","font-size":"200%"});
            

             

jQuery height() and width() Methods

 

Example

$("#div1").height("200px");        

              

Example

$("#div2").width("300px");        

jQuery CSS Methods From this Page:

 

CSS, Styling, & Dimensions

Note

CSS properties that normally include a hyphen need to be
camel cased in JavaScript. For example, the CSS property font-size is expressed
as fontSize when used as a property name in JavaScript. This does not apply,
however, when passing the name of a CSS property to the $.fn.css method as a
string — in that case, either the camel cased or hyphenated form will work.

 

1          $(‘h1’).css(‘fontSize’);
// returns a string such as "19px"              

2          $(‘h1’).css(‘font-size’);
// also works                

 

1          $(‘h1’).css(‘fontSize’,
‘100px’); // setting an individual property                          

2          $(‘h1’).css({
‘fontSize’ : ‘100px’, ‘color’ : ‘red’ }); // setting multiple properties

Note the style of the argument we use on the second line
— it is an object that contains multiple properties. This is a common way to
pass multiple arguments to a function, and many jQuery setter methods accept
objects to set mulitple values at once.

Manipulating Properties

Dimensions

jQuery offers a variety of methods for obtaining and
modifying dimension and position information about an element.

The code in “Basic dimensions methods”, is just a very
brief overview of the dimensions functionality in jQuery; for complete details
about jQuery dimension methods, visit http://api.jquery.com/category/dimensions/
.

Example 3.21: Basic dimensions methods

view sourceprint?

 

1          $(‘h1′).width(’50px’);  
// sets the width of all H1 elements         

2          $(‘h1’).width();        
// gets the width of the first H1                 

4          $(‘h1′).height(’50px’); 
// sets the height of all H1 elements       

5          $(‘h1’).height();       
// gets the height of the first H1       

7          $(‘h1’).position();     
// returns an object containing position                  

8                                   //
information for the first H1 relative to          

9                                   //
its "offset (positioned) parent"        

Attributes

An element’s attributes can contain useful information
for your application, so it’s important to be able to get and set them.

The $.fn.attr method acts as both a getter and a setter.
As with the $.fn.css method, $.fn.attr as a setter can accept either a key and
a value, or an object containing one or more key/value pairs.

 

1          $(‘a’).attr(‘href’,
‘allMyHrefsAreTheSameNow.html’);    

2          $(‘a’).attr({
                   

3              ‘title’
: ‘all titles are the same too!’,       

4              ‘href’
: ‘somethingNew.html’                       

5          });       

 

 

$("#aGoogle1").attr("href")

$("#aGoogle2").attr("href", "http://www.google.co.uk");

$("#aGoogle3").attr( { "href" :
"http://www.google.co.uk",
"title" : "Google.co.uk" });

 

 HTML Fields Value.

 

How to get HTML fields value.

Text field: $(‘#name’).val();

Drop Down: $(‘#category option:selected’).val();

Radio Or Check Box: $(‘#checkid’).attr(‘checked’); //
return true if checked other wise false;

HTML content : $(‘#div’).html(); // same as innerHTML of
DOM

 

How to set value of HTML fields.

Text field: $(‘#name’).val(‘test’);

Drop Down: $(‘#category option:selected’).val(‘ABC’);

Radio Or Check Box: $(‘#checkid’).attr(‘checked’,true);
or $(‘#checkid’).attr(‘checked’,false);

HTML content :
$(‘#div’).html(‘<table><tr><td>Test</td></tr></table>’);

 

How use animated effects or simple show hide like
document.getElementById().style.display=block; of DOM

Regular Expression

 

How to use regular expression.

If you want remove blank space from a string

$(‘#title’).val().replace(/^\s+|\s+$/g, ”) == ”)

Check format through regular expression like email id
validation.

var pattern = new
RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

pattern.test(‘subranild@mindfiresolutions.com’ ); //
return true or false.

AJAX Old

 

For using AJAX you don’t need to create all
XMLHttpRequest or ActiveXObject object.

You just need to determine which method you like GET or
POST and you done with your AJAX .

 

$.post(

  ‘send-to-friend.php’,

  {your_name:$(‘#your_name’).val(),

               
your_email:$(‘#your_email’).val()

               
comments:$(‘#comments’).val()

               
}

  ,function(result){

  $(‘#div’).html(result);

               
//here you call your function based upon ajax response.

 });

       

another way you can do this

 

function LoadCategoryToEdit(cat_id)

{

 $.post(

  ‘get_categories_page.php’,

  {cat_id:cat_id}

  ,LoadCategoryCallback

 );

}

function LoadCategoryCallback(result) {

 $(‘#divCategoryForm’).html(result);

 ShowCategoryForm();

}

 

If you send the result in JSON format then

 

$.get(

  ‘send-to-friend.php’,

  {your_name:$(‘#your_name’).val(),

               
your_email:$(‘#your_email’).val()

               
comments:$(‘#comments’).val()

               
}

  ,function(result){

  result = JSON.decode(result);

               
//here you call your function based upon ajax response.

 });

           

Inline JS

 

<a href="javascript:void(0);"
onclick="$(this).toggleClass(‘bold’);">Toggle class</a>

 

 $(‘<%=Button1.ClientID %>’).hover(

           function
() {

              
$(this).text = $(this).text + ‘1’;

           }

////////////////////////////////////////////////////////////////

#foo > * > * > .bar

(all elements with class "bar" which are great
grandchildren of the element with id "foo")

////////////////////////////////////////////////////////////////

Learning the basics

Using $(‘li:eq(2)’) will get the third list item (note
that counting array items in JavaScript, and therefore jQuery, start at 0).
While I hate to be confusing about things like this, you should also know that
$(‘li:nth-child(3)’) will also get the element. Why does nth-child() start
counting at 1? It’s due to the fact that CSS is what is called ‘1-indexed’ and
the selector nth-child() was born in CSS world, not JavaScript.

If you have more than one list in your web page, you’ll
need to be more specific with the selector if you’re trying to match one item
in one list. In the case of the list illustrated you could use $(‘#list
li:eq(2)’) or $(‘#list li:nth-child(3)’) to get the third item.

 

Taming selectors

One of the things that you really need to be aware of
when using jQuery is that selectors are read from right-to-left by the jQuery
selector engine,. What this means is that lengthy selectors are more
resource-intensive and may take additional time to perform. view sourceprint?

 

1          var $divs
= $(‘div’);     

Note

In “Storing selections in a variable”, the variable name
begins with a dollar sign. Unlike in other languages, there’s nothing special
about the dollar sign in JavaScript — it’s just another character. We use it
here to indicate that the variable contains a jQuery object. This practice — a
sort of Hungarian notation  — is merely
convention, and is not mandatory.

Once you’ve stored your selection, you can call jQuery
methods on the variable you stored it in just like you would have called them
on the original selection.

Note

A selection only fetches the elements that are on the
page when you make the selection. If you add elements to the page later, you’ll
have to repeat the selection or otherwise add them to the selection stored in
the variable. Stored selections don’t magically update when the DOM changes.

 

Learning advanced selectors

$(‘div[class^="yellow"]’)

How about selecting all of the items that have classes
beginning with yellow OR having the class triangle?

$(‘div[class^="yellow"],[class~="triangle"]’)

Here the ~ (tilde) signifies that the attribute selector
should look for items where the class "contains the word" triangle.
By separating the attribute selectors with a comma you are providing an OR
condition to the search. If you remove the comma the AND condition is invoked
and will not return any object because there’s no element with the class of
"yellow triangle". You can continue to chain together attribute
selectors together when working with jQuery.

 

Using selectors with forms

You can use jQuery’s attribute selectors for working with
forms and these types of selectors are often perfect for achieving a particular
effect such as clearing a form after it is submitted:

$(‘input[type="text"]’).val(”);

If you want to clear other input elements you can put
additional attribute definitions into the selector:

$(‘input[type="text"],[type="number]’).val(”);

Use caution, though! I’ve seen many a developer use the
following selector and wonder why their form, buttons and all, empties out:

$(‘input’).val(”);

All of the form’s input values will be cleared, including
text on any submit or reset elements included in the form. It’s a good lesson
in being specific with your jQuery selectors.

Using $(‘form[name="myForm"] input:checked’)
will wrap the input with the checkbox having the CHECKED property. If you want
to select all inputs from your form, and it is the only form on the page, you
can use $(‘:input’).

 

////////////////////////////////////////////////////////////////

 

jQuery child and sibling selectors can divide into four
selectors, descendant selector (A B), child selector (A > B), adjacent
sibling selector (A + B) and general sibling selector (A ~ B). Let go through
an example to understand the different in between.

 

1. Descendant selector (A B)

            $(".person1
div").css("border", "2px solid red");

2. Child selector (A > B)

            $(".person1
> div").css("border", "2px solid red");

3. Adjacent sibling selector (A + B)

            $(".person1
+ p").css("border", "2px solid red");

4. General sibling selector (A ~ B)

General sibling selector is used to select all elements
matched by “B” that is a sibling of a “A” element.

            $(".person1
~ p").css("border", "2px solid red");

 

////////////////////

 

JQuery – Nth-Child Selector Example

 

The jQuery nth-child is used to select all elements that
are ntg-child of of their parent. The nth-child(n) is “1-indexed”, meaning the
“n” is counting starts at 1.

 

For example,

1. $(‘tr:nth-child(3)’) – selects all elements matched by
<tr> that are the third child of their parent.

2. $(‘tr:nth-child(3n)’) – selects all elements matched
by <tr> that are every third child of their parent.

3. $(‘tr:nth-child(even)’) – selects all elements matched
by <tr> that are the even child of their parent.

/////////////////

JQuery – First Child & Last Child Selector Example

 

The :first-child is used to select all elements that are
the first child of their parent, which is a shorthand for :nth-child(1).

Examples

$(‘li:first-child’) – selects all elements matched by
<li> that are the first child of their parent.

$(tr:first-child’) – selects all elements matched by
<tr> that are the first child of their parent.

The :last-child is used to select all elements that are
the last child of their parent.

Examples

$(‘li:last-child’) – selects all elements matched by
<li> that are the last child of their parent.

$(tr:last-child’) – selects all elements matched by
<tr> that are the last child of their parent.

jQuery Example

 

///////////////////////////

Only Child Selector Example

The “only-child” is used to select all elements that are
the only child of their parent.

Examples

$(‘:only-child’) – selects all elements that are the only
child of their parent.

$(‘li:only-child’) – selects all elements matched by
<li> that are the only child of their parent.

JQ Selector Functions

The prev() function is used to get the immediate
preceding sibling element in the set of matched elements. Only the previous
sibling’s element is select, it’s child element will be ignore.

 

This prev() function is allow to filter it by ‘selector’.
For example, prev(‘div’) is used to get the immediate preceding sibling
elements that are <div> elements only.

///////////////////////////

In jQuery, children() is used to find the child of the
matched elements, it’s only travels a single level down.

$(‘.A1’).children().css(‘background’,’red’);

 

            $(‘.A1’).children().css(‘background’,’red’);

 

 

You mean something like this?

$(‘.click-me’).click(function() {

    var
$theAncestor = $(this).closest(‘#ancestor-1’);

}

Given the click-me example, if you would like to have a
set of all of an element’s ancestors returned, use:

$(this).parents()

or

$(this).parents(selector)

But be aware that this will traverse through ALL
ancestors returning all, or all that match when a selector is given.

If you would like to have the immediate parent returned,
use:

$(this).parent()

If you know which ancestor you need, use:

$(this).closest(selector)

But be aware that it will only return the first match,
and if the current element (this) is a match, it will return that.

 

Try using parents() or closest() in combination, perhaps,
with a selector to determine which ancestor should match. For example, find the
closest ancestor div with an id.

$(‘.click-me’).click( function() {

      var
ancestorId = $(this).closest(‘div[id]’);

     
alert(ancestorId);

});

Filter & Find

 

filter will select a certain subset (zero or more) of the
already

selected elements.

find will select a set of (zero or more) elements that
are descendants of the already selected elements.

//////////////////////////////////////////////////////////////////////////Part
2//////////////////////////////////////////////////////////

NaN

Now what is NaN. NaN states for Not a Number. It’s a
value which a variable of type Number can hold meaning that it holds something
which is not a number. This is how you can get NaN:

 

Number( "hello" );

0/0;

Math.sqrt( -1 );

The only way you can check if your variable holds NaN is
isNaN() global function. You can’t say

 

1          something
== NaN;     

because comparing to NaN always results in false. Even

 

1          NaN ==
NaN   

is false.

There’s another value for Numbers you should know —
Infinity. You can get it if you divide something by 0.

private var undef: *;

 

trace( {}.x ); // undefined

trace( undef ); // undefined

trace( [][1] ); // undefined

trace( Number( "hello" ) ); // NaN

trace( 0/0 ); // NaN

trace( Math.sqrt( -1 ) ); // NaN

trace( 1/0 ); // Infinity

trace( NaN == undefined ); // false

trace( NaN === undefined ); // false

trace( null
== undefined ); // true

trace( null === undefined ); // false

trace( NaN == NaN ); // false

trace( NaN === NaN ); // false

trace( null == null ); // true

trace( null === null ); // true

trace( undefined == undefined ); // true

trace( undefined === undefined ); // true        

 

Operators:

 

·           console.log()
for sending general log messages

·           console.dir()
for logging a browseable object

·           console.warn()
for logging warnings

·           console.error()
for logging error messages

 

1          var foo =
1;                     

2          var bar =
‘2’;      

4          console.log(foo
+ bar);  // 12. uh oh   

Number(bar)

The Number constructor, when called as a function (like
above) will have the effect of casting its argument into a number. You could
also use the unary plus operator, which does the same thing:

(using the unary-plus operator)

1          console.log(foo
+ +bar);         

 

01        var foo =
1;         

02        var bar =
0;       

03        var baz =
2;         

05        foo ||
bar;   // returns 1, which is true      

06        bar ||
foo;   // returns 1, which is true    

08        foo
&& bar;   // returns 0, which is false          

09        foo
&& baz;   // returns 2, which is true             

10        baz
&& foo;   // returns 1, which is true         

Though it may not be clear from the example, the || operator
returns the value of the first truthy operand, or, in cases where neither
operand is truthy
, it’ll return the last of both operands. The &&
operator returns the value of the first false operand, or the value of the last
operand if both operands are truthy.

Be sure to consult the section called “Truthy and Falsy
Things”  for more details on which values
evaluate to true and which evaluate to false.

Comparison Operators

Comparison operators allow you to test whether values are
equivalent or whether values are identical.

Example 2.12: Comparison operators

view sourceprint?

01        var foo =
1;         

02        var bar =
0;       

03        var baz =
‘1’;       

04        var bim =
2;                  

06        foo ==
bar;   // returns false      

07        foo !=
bar;   // returns true                       

08        foo ==
baz;   <SPAN class=bold><STRONG>// returns true;
careful!</STRONG></SPAN>     

10        foo ===
baz;             //
returns false      

11        foo !==
baz;             //
returns true          

12        foo ===
parseInt(baz);   // returns true              

14        foo >
bim;    // returns false      

15        bim >
baz;    // returns true          

16        foo <=
baz;   // returns true     

Truthy and Falsy Things

In order to use flow control successfully, it’s important
to understand which kinds of values are "truthy" and which kinds of
values are "falsy." Sometimes, values that seem like they should
evaluate one way actually evaluate another.

 

1          ‘0’;                       

2          ‘any
string’;       

3          []; 
// an empty array                   

4          {}; 
// an empty object  

5          1;  
// any non-zero number    

 

1          0;                        

2          ”; 
// an empty string      

3          NaN; //
JavaScript’s "not-a-number" variable      

4          null;                  

5          undefined; 
// be careful — undefined can be redefined!        

Loops

 

1          // logs
‘try 0’, ‘try 1’, …, ‘try 4’      

2          for (var
i=0; i<5; i++) {                         

 

3              console.log(‘try
‘ + i);              

4          }                     

Note that in Loops even though we use the keyword var
before the variable name i, this does not "scope" the variable i to
the loop block. We’ll discuss scope in depth later in this chapter.

Arrays

 

var myArray = [ ‘hello’, ‘world’ ];        

1          var
myArray = [ ‘hello’, ‘world’, ‘foo’, ‘bar’ ];      

2          console.log(myArray[3]);  
// logs ‘bar’            

 

1          var
myArray = [ ‘hello’, ‘world’ ];                        

2          console.log(myArray.length);  
// logs 2          

 

1          var
myArray = [ ‘hello’, ‘world’ ];            

2          myArray[1]
= ‘changed’;                     

While it’s possible to change the value of an array item
as shown in “Changing the value of an array item”, it’s generally not advised.

 

1          var
myArray = [ ‘hello’, ‘world’ ];            

2          myArray.push(‘new’);             

 

1          var
myArray = [ ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ ];                      

2          var
myString = myArray.join(”);   // ‘hello’        

 

3          var
mySplit = myString.split(”);  // [ ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ ]  

Functions

 

1          function
foo() { /* do something */ } 

Example 2.33: Named Function Expression

1          var foo =
function() { /* do something */ }    

Self-Executing Anonymous Functions

            A common
pattern in JavaScript is the self-executing anonymous function. This pattern
creates a function expression and then immediately executes the function. This
pattern is extremely useful for cases where you want to avoid polluting the
global namespace with your code — no variables declared inside of the function
are visible outside of it.

 

1          (function(){
                   

2              var
foo = ‘Hello world’;         

  3        })();                   
                        

6          console.log(foo);  
// undefined!         

Scope

When a variable is declared inside of a function using
the var keyword, it is only available to code inside of that function — code
outside of that function cannot access the variable. On the other hand,
functions defined inside that function will have access to to the declared
variable.

Furthermore, variables
that are declared inside a function without the var keyword are not local to
the function
— JavaScript will traverse the scope chain all the way up to
the window scope to find where the variable was previously defined. If the
variable wasn’t previously defined, it will be defined in the global scope,
which can have extremely unexpected consequences;

 

1          var foo =
‘hello’;             

3          var
sayHello = function() {         

4              console.log(foo);
                 

5          };            

7          sayHello();        
// logs ‘hello’                 

8          console.log(foo);  
// also logs ‘hello’   

Closures

Closures are an extension of the concept of scope —
functions have access to variables that were available in the scope where the
function was created. If that’s confusing, don’t worry: closures are generally
best understood by example.

In “Functions can "see" changes in variable
values after the function is defined”, we saw how functions have access to
changing variable values. The same sort of behavior exists with functions
defined within loops — the function "sees" the change in the
variable’s value even after the function is defined, resulting in all clicks
alerting 5.

1          /* this
won’t behave as we want it to; */             

2          /* every
click will alert 5 */                

  3        for (var i=0; i<5; i++) {                           

4              $(‘<p>click
me</p>’).appendTo(‘body’).click(function() {    

5                  alert(i);
       

6              });
                

7          }         

Example 2.50: Locking in the value of i with a closure

view sourceprint?

 

1          /* fix:
“close” the value of i inside createFunction, so it won’t change */          

2          var
createFunction = function(i) {                     

 

3              return
function() { alert(i); };              

4          };                      

 

5           
                        

6          for (var
i=0; i<5; i++) {             

 

7              $(‘<p>click
me</p>’).appendTo(‘body’).click(createFunction(i));        

8          }                     

Closures can also be used to resolve issues with the this
keyword, which is unique to each scope:

Example 2.51: Using a closure to access inner and outer
object instances simultaneously

view sourceprint?

 

01        var
outerObj = {                          

02            myName
: ‘outer’,     

 

03            outerFunction
: function () {               

04         
                     

 

05                //
provide a reference to outerObj through innerFunction’s closure             

06                var
self = this;                   

08                var
innerObj = {    

  09                  myName
: ‘inner’,                       

10                    innerFunction
: function () {     

  11                      console.log(self.myName,
this.myName); // logs ‘outer inner’            

12                    }
                      

  13              };
               

 

15                innerObj.innerFunction();
              

17                console.log(this.myName);
// logs ‘outer’                

18            }
                  

19        };              

21        outerObj.outerFunction();       

This mechanism can be particularly useful when dealing with
callbacks, though in those cases, it is often better to use Function.bind ,
which will avoid any overhead associated with scope traversal.

 

/////////////////

$(document).ready()

You cannot safely manipulate a page until the document is
“ready.” jQuery detects this state of readiness for you; code included inside
$(document).ready() will only run once the page is ready for JavaScript code to
execute.

 

1          $(‘input[name=first_name]’);
// beware, this can be very slow

1          $(‘#contents
ul.people li’);       

1          $(‘a.external:first’);
         

2          $(‘tr:odd’);
                    

3          $(‘#myForm
:input’);   // select all input-like elements in a form             

4          $(‘div:visible’);
                         

5          $(‘div:gt(2)’);       
// all except the first three divs            

6          $(‘div:animated’);    
// all currently animated divs                  

Note

When you use the :visible and :hidden pseudo-selectors,
jQuery tests the actual visibility of the element, not its CSS visibility or
display — that is, it looks to see if the element’s physical height and width
on the page are both greater than zero. However, this test doesn’t work with
<tr> elements; in this case, jQuery does check the CSS display property,
and considers an element hidden if its display property is set to none.
Elements that have not been added to the DOM will always be considered hidden,
even if the CSS that would affect them would render them visible. (See the
Manipulation section later in this chapter to learn how to create and add
elements to the DOM.)

Choosing Selectors

 

 

1          // find
all <a>s whose rel attribute           

2          // ends
with "thinger"                

3          $("a[rel$=’thinger’]");  

Does My Selection Contain Any Elements?

Instead, you need to test the selection’s length
property, which tells you how many elements were selected. If the answer is 0,
the length property will evaluate to false when used as a boolean value.

Example 3.9: Testing whether a selection contains
elements

view sourceprint?

 

1          if
($(‘div.foo’).length) { … }    

Saving Selections

Every time you make a selection, a lot of code runs, and jQuery
doesn’t do caching of selections for you. If you’ve made a selection that you
might need to make again, you should save the selection in a variable rather
than making the selection repeatedly.

Example 3.10: Storing selections in a variable

view sourceprint?

 

1          var $divs
= $(‘div’);     

Note

In “Storing selections in a variable”, the variable name
begins with a dollar sign. Unlike in other languages, there’s nothing special
about the dollar sign in JavaScript — it’s just another character. We use it
here to indicate that the variable contains a jQuery object. This practice — a
sort of Hungarian notation  — is merely
convention, and is not mandatory.

Once you’ve stored your selection, you can call jQuery
methods on the variable you stored it in just like you would have called them
on the original selection.

Note

A selection only fetches the elements that are on the
page when you make the selection. If you add elements to the page later, you’ll
have to repeat the selection or otherwise add them to the selection stored in
the variable. Stored selections don’t magically update when the DOM changes.

Traversing

Once you have a jQuery selection, you can find other
elements using your selection as a starting point.

For complete documentation of jQuery traversal methods,
visit http://api.jquery.com/category/traversing/
.

Note

Be cautious with traversing long distances in your
documents — complex traversal makes it imperative that your document’s structure
remain the same, something that’s difficult to guarantee even if you’re the one
creating the whole application from server to client. One- or two-step
traversal is fine, but you generally want to avoid traversals that take you
from one container to another.

Example 3.24: Moving around the DOM using traversal
methods

view sourceprint?

 

1          $(‘h1’).next(‘p’);
                         

2          $(‘div:visible’).parent();
            

 

3          $(‘input[name=first_name]’).closest(‘form’);
      

4          $(‘#myList’).children();
                        

 

5          $(‘li.selected’).siblings();         

You can also iterate over a selection using $.fn.each.
This method iterates over all of the elements in a selection, and runs a
function for each one. The function receives the index of the current element
and the DOM element itself as arguments. Inside the function, the DOM element
is also available as this by default.

Example 3.25: Iterating over a selection

view sourceprint?

 

1          $(‘#myList
li’).each(function(idx, el) {                

2              console.log(
                         

 

3                  ‘Element
‘ + idx +                            

4                  ‘has
the following html: ‘ +            

 

5                  $(el).html()
            

6              );
                  

 

7          });       

Manipulating Elements

Once you’ve made a selection, the fun begins. You can
change, move, remove, and clone elements. You can also create new elements via
a simple syntax.

For complete documentation of jQuery manipulation
methods, visit http://api.jquery.com/category/manipulation/
.

Getting and Setting Information about Elements

Manipulating Attributes

 

jQuery Core

$ vs $()

Until now, we’ve been dealing entirely with methods that
are called on a jQuery object. For example:

view sourceprint?

 

1          $(‘h1’).remove();         

Most jQuery methods are called on jQuery objects as shown
above; these methods are said to be part of the $.fn namespace, or the “jQuery
prototype,” and are best thought of as jQuery object methods.

However, there are several methods that do not act on a
selection; these methods are said to be part of the jQuery namespace, and are
best thought of as core jQuery methods.

 

·           Methods
called on jQuery selections are in the $.fn namespace, and automatically
receive and return the selection as this.

·           Methods
in the $ namespace are generally utility-type methods, and do not work with
selections; they are not automatically passed any arguments, and their return
value will vary.

There are a few cases where object methods and core
methods have the same names, such as $.each and $.fn.each. In these cases, be
extremely careful when reading the documentation that you are exploring the
correct method.

Utility Methods

jQuery offers several utility methods in the $ namespace.
These methods are helpful for accomplishing routine programming tasks. Below
are examples of a few of the utility methods; for a complete reference on
jQuery utility methods, visit http://api.jquery.com/category/utilities/
.

$.trim

Removes leading and trailing whitespace.

view sourceprint?

 

1          $.trim(‘   
lots of extra whitespace    ‘);                

2          //
returns ‘lots of extra whitespace’                  

$.each

Iterates over arrays and objects.

view sourceprint?

 

1          $.each([
‘foo’, ‘bar’, ‘baz’ ], function(idx, val) {              

2              console.log(‘element
‘ + idx + ‘is ‘ + val);                  

 

3          });           

4           
                    

 

5          $.each({
foo : ‘bar’, baz : ‘bim’ }, function(k, v) {           

6              console.log(k
+ ‘ : ‘ + v);                   

 

7          });       

Note

There is also a method $.fn.each, which is used for
iterating over a selection of elements.

$.inArray

Returns a value’s index in an array, or -1 if the value
is not in the array.

view sourceprint?

 

1          var
myArray = [ 1, 2, 3, 5 ];        

2                                 

 

3          if
($.inArray(4, myArray) !== -1) {        

4              console.log(‘found
it!’);                     

 

5          }         

$.extend

Changes the properties of the first object using the
properties of subsequent objects.

view sourceprint?

 

1          var
firstObject = { foo : ‘bar’, a : ‘b’ };    

2          var
secondObject = { foo : ‘baz’ };                    

 

3           
                       

4          var
newObject = $.extend(firstObject, secondObject);              

 

5          console.log(firstObject.foo);
// ‘baz’        

6          console.log(newObject.foo);  
// ‘baz’  

If you don’t want to change any of the objects you pass
to $.extend, pass an empty object as the first argument.

view sourceprint?

 

1          var firstObject
= { foo : ‘bar’, a : ‘b’ };    

2          var
secondObject = { foo : ‘baz’ };                    

 

3           
                       

4          var
newObject = $.extend({}, firstObject, secondObject);        

 

5          console.log(firstObject.foo);
// ‘bar’        

6          console.log(newObject.foo);  
// ‘baz’  

$.proxy

Returns a function that will always run in the provided
scope — that is, sets the meaning of this inside the passed function to the
second argument.

view sourceprint?

 

1          var
myFunction = function() { console.log(this); };        

2          var
myObject = { foo : ‘bar’ };                          

 

3           
                       

4          myFunction();
// logs window object     

 

5           
                       

6          var
myProxyFunction = $.proxy(myFunction, myObject);       

 

7          myProxyFunction();
// logs myObject object   

If you have an object with methods, you can pass the object
and the name of a method to return a function that will always run in the scope
of the object.

view sourceprint?

 

1          var
myObject = {                        

2              myFn
: function() {  

 

3                  console.log(this);
               

4              }
                  

 

5          };            

6           
                    

 

7          $(‘#foo’).click(myObject.myFn);
// logs DOM element #foo                   

8          $(‘#foo’).click($.proxy(myObject,
‘myFn’)); // logs myObject 

Checking types

As mentioned in the "JavaScript basics"
section, jQuery offers a few basic utility methods for determining the type of
a specific value.

Example 4.1: Checking the type of an arbitrary value

view sourceprint?

 

01        var
myValue = [1, 2, 3];             

02                               

 

03        // Using
JavaScript’s typeof operator to test for primative types              

04        typeof
myValue == ‘string’; // false                   

 

05        typeof
myValue == ‘number’; // false                  

06        typeof
myValue == ‘undefined’; // false            

 

07        typeof
myValue == ‘boolean’; // false    

08         
                     

 

09        // Using
strict equality operator to check for null            

10        myValue
=== null; // false                    

 

11         
                        

12        // Using
jQuery’s methods to check for non-primative types     

 

13        jQuery.isFunction(myValue);
// false                  

14        jQuery.isPlainObject(myValue);
// false            

 

15        jQuery.isArray(myValue);
// true        

Events

Overview

jQuery provides simple methods for attaching event
handlers to selections. When an event occurs, the provided function is
executed. Inside the function, this refers to the element that was clicked.

For details on jQuery events, visit http://api.jquery.com/category/events/
.

The event handling function can receive an event object.
This object can be used to determine the nature of the event, and to prevent
the event’s default behavior.

For details on the event object, visit http://api.jquery.com/category/events/event-object/
.

Connecting Events to Elements

 

Inside the Event Handling Function

As mentioned in the overview, the event handling function
receives an event object, which contains many properties and methods. The event
object is most commonly used to prevent the default action of the event via the
preventDefault method. However, the event object contains a number of other useful
properties and methods, including:

pageX, pageY

The mouse position at the time the event occurred,
relative to the top left of the page.

type

The type of the event (e.g. "click").

which

The button or key that was pressed.

data

Any data that was passed in when the event was bound.

target

The DOM element that initiated the event.

preventDefault()

Prevent the default action of the event (e.g. following a
link).

stopPropagation()

Stop the event from bubbling up to other elements.

In addition to the event object, the event handling
function also has access to the DOM element that the handler was bound to via
the keyword this. To turn the DOM element into a jQuery object that we can use
jQuery methods on, we simply do $(this), often following this idiom:

view sourceprint?

 

1          var $this
= $(this);       

Preventing a link from being followed

view sourceprint?

 

1          $(‘a’).click(function(e)
{             

2              var
$this = $(this);                 

 

3              if
($this.attr(‘href’).match(‘evil’)) {      

4                  e.preventDefault();
                      

 

5                  $this.addClass(‘evil’);
         

6              }
                  

 

7          });       

Triggering Event Handlers

jQuery provides a way to trigger the event handlers bound
to an element without any user interaction via the $.fn.trigger method. While
this method has its uses, it should not be used simply to call a function that
was bound as a click handler. Instead, you should store the function you want
to call in a variable, and pass the variable name when you do your binding.
Then, you can call the function itself whenever you want, without the need for
$.fn.trigger.

Triggering an event handler the right way

view sourceprint?

 

01        var foo =
function(e) {               

02            if
(e) {                       

 

03                console.log(e);
       

04            }
else {                      

 

05                console.log(‘this
didn\’t come from an event!’);      

06            }
                  

 

07        };            

08         
                     

 

09         
                        

10        $(‘p’).click(foo);
           

 

11         
                        

12        foo(); //
instead of $(‘p’).trigger(‘click’)           

Increasing Performance with Event Delegation

You’ll frequently use jQuery to add new elements to the
page, and when you do, you may need to bind events to those new elements —
events you already bound to similar elements that were on the page originally.
Instead of repeating your event binding every time you add elements to the
page, you can use event delegation. With event delegation, you bind your event
to a container element, and then when the event occurs, you look to see which
contained element it occurred on. If this sounds complicated, luckily jQuery
makes it easy with its $.fn.live and $.fn.delegate methods.

While most people discover event delegation while dealing
with elements added to the page later, it has some performance benefits even if
you never add more elements to the page. The time required to bind event
handlers to hundreds of individual elements is non-trivial; if you have a large
set of elements, you should consider delegating related events to a container
element.

Note

The $.fn.live method was introduced in jQuery 1.3, and at
that time only certain event types were supported. As of jQuery 1.4.2, the
$.fn.delegate method is available, and is the preferred method.

Event delegation using $.fn.delegate

view sourceprint?

 

1          $(‘#myUnorderedList’).delegate(‘li’,
‘click’, function(e) {            

2              var
$myListItem = $(this);                

 

3              //
   

4          });                   

Event delegation using $.fn.live

view sourceprint?

 

1          $(‘#myUnorderedList
li’).live(‘click’, function(e) {         

2              var
$myListItem = $(this);                

 

3              //
   

4          });                   

Unbinding Delegated Events

If you need to remove delegated events, you can’t simply
unbind them. Instead, use $.fn.undelegate for events connected with
$.fn.delegate, and $.fn.die for events connected with $.fn.live. As with bind,
you can optionally pass in the name of the bound function.

Unbinding delegated events

view sourceprint?

 

1          $(‘#myUnorderedList’).undelegate(‘li’,
‘click’);                

2          $(‘#myUnorderedList
li’).die(‘click’);              

Event Helpers

jQuery offers two event-related helper functions that save
you a few keystrokes.

$.fn.hover

The $.fn.hover method lets you pass one or two functions
to be run when the mouseenter and mouseleave events occur on an element. If you
pass one function, it will be run for both events; if you pass two functions,
the first will run for mouseenter, and the second will run for mouseleave.

Note

Prior to jQuery 1.4, the $.fn.hover method required two
functions.

The hover helper function

view sourceprint?

 

1          $(‘#menu
li’).hover(function() {                          

2              $(this).toggleClass(‘hover’);
 

 

3          });       

$.fn.toggle

The $.fn.toggle method is triggered by the
"click" event and accepts two or more functions. Each time the click
event occurs, the next function in the list is called. Generally, $.fn.toggle is
used with just two functions; however, it will accept an unlimited number of
functions. Be careful, though: providing a long list of functions can be
difficult to debug).

The toggle helper function

view sourceprint?

 

1          $(‘p.expander’).toggle(
               

2              function()
{               

 

3                  $(this).prev().addClass(‘open’);
      

4              },
                 

 

5              function()
{                 

6                  $(this).prev().removeClass(‘open’);
          

 

7              }
        

8          );                     

Exercises

Create an Input Hint

Open the file /exercises/index.html in your browser. Use
the file /exercises/js/inputHint.js or work in Firebug. Your task is to use the
text of the label for the search input to create "hint" text for the
search input. The steps are as follows:

1.         Set the
value of the search input to the text of the label element

2.         Add a
class of "hint" to the search input

3.         Remove
the label element

4.         Bind a
focus event to the search input that removes the hint text and the
"hint" class

5.         Bind a
blur event to the search input that restores the hint text and "hint"
class if no search text was entered

What other considerations might there be if you were
creating this functionality for a real site?

Add Tabbed Navigation

Open the file /exercises/index.html in your browser. Use
the file /exercises/js/tabs.js. Your task is to create tabbed navigation for
the two div.module elements. To accomplish this:

1.         Hide all
of the modules.

2.         Create an
unordered list element before the first module.

3.         Iterate over
the modules using $.fn.each. For each module, use the text of the h2 element as
the text for a list item that you add to the unordered list element.

4.         Bind a
click event to the list item that:

o          Shows the
related module, and hides any other modules

o          Adds a
class of "current" to the clicked list item

o          Removes
the class "current" from the other list item

5.         Finally,
show the first tab.

Custom Effects with $.fn.animate

jQuery makes it possible to animate arbitrary CSS
properties via the $.fn.animate method. The $.fn.animate method lets you
animate to a set value, or to a value relative to the current value.

Example 6.6: Custom effects with $.fn.animate

view sourceprint?

 

1          $(‘div.funtimes’).animate(
          

2              {
                  

 

3                  left
: "+=50",           

4                  opacity
: 0.25        

 

5              },
                   

6              300,
// duration         

 

7              function()
{ console.log(‘done!’); // calback                

8          });                   

Note

Color-related properties cannot be animated with
$.fn.animate using jQuery out of the box. Color animations can easily be
accomplished by including the color plugin . We’ll discuss using plugins later
in the book.

Easing

[Definition: Easing describes the manner in which an
effect occurs — whether the rate of change is steady, or varies over the
duration of the animation.] jQuery includes only two methods of easing: swing
and linear. If you want more natural transitions in your animations, various
easing plugins are available.

As of jQuery 1.4, it is possible to do per-property
easing when using the $.fn.animate method.

Example 6.7: Per-property easing

view sourceprint?

 

1          $(‘div.funtimes’).animate(
          

2              {
                  

 

3                  left
: [ "+=50", "swing" ],                            

4                  opacity
: [ 0.25, "linear" ]             

 

5              },
                   

6              300
 

 

7          );         

For more details on easing options, see http://api.jquery.com/animate/ .

Managing Effects

jQuery provides several tools for managing animations.

$.fn.stop

Stop currently running animations on the selected elements.

$.fn.delay

Wait the specified number of milliseconds before running
the next animation.

view sourceprint?

 

1          $(‘h1’).show(300).delay(1000).hide(300);      

jQuery.fx.off

If this value is true, there will be no transition for
animations; elements will immediately be set to the target final state instead.
This can be especially useful when dealing with older browsers; you also may
want to provide the option to your users.

 

Optimize Selectors

Selector optimization is less important than it used to
be, as more browsers implement document.querySelectorAll() and the burden of
selection shifts from jQuery to the browser. However, there are still some tips
to keep in mind.

ID-Based Selectors

Beginning your selector with an ID is always best.

view sourceprint?

 

1          // fast                  

2          $(‘#container
div.robotarm’);    

 

3           
                       

4          //
super-fast       

 

5          $(‘#container’).find(‘div.robotarm’);    

The $.fn.find approach is faster because the first
selection is handled without going through the Sizzle selector engine — ID-only
selections are handled using document.getElementById(), which is extremely fast
because it is native to the browser.

Specificity

Be specific on the right-hand side of your selector, and
less specific on the left.

view sourceprint?

 

1          //
unoptimized                 

2          $(‘div.data
.gonzalez’);              

 

3           
                       

4          //
optimized       

 

5          $(‘.data
td.gonzalez’);  

Use tag.class if possible on your right-most selector,
and just tag or just .class on the left.

Avoid excessive specificity.

view sourceprint?

 

1          $(‘.data
table.attendees td.gonzalez’);      

2                                 

 

3          //
better: drop the middle if possible       

4          $(‘.data
td.gonzalez’);              

A "flatter" DOM also helps improve selector performance,
as the selector engine has fewer layers to traverse when looking for an
element.

Avoid the Universal Selector

Selections that specify or imply that a match could be
found anywhere can be very slow.

view sourceprint?

 

1          $(‘.buttons
> *’);  // extremely expensive            

2          $(‘.buttons’).children(); 
// much better                          

 

3           
                       

4          $(‘.gender
:radio’);  // implied universal selection          

 

5          $(‘.gender
*:radio’); // same thing, explicit now               

6          $(‘.gender
input:radio’); // much better            

Use Event Delegation

Event delegation allows you to bind an event handler to
one container element (for example, an unordered list) instead of multiple
contained elements (for example, list items). jQuery makes this easy with
$.fn.live and $.fn.delegate. Where possible, you should use $.fn.delegate
instead of $.fn.live, as it eliminates the need for an unnecessary selection,
and its explicit context (vs. $.fn.live’s context of document) reduces overhead
by approximately 80%.

In addition to performance benefits, event delegation
also allows you to add new contained elements to your page without having to
re-bind the event handlers for them as they’re added.

view sourceprint?

 

1          // bad
(if there are lots of list items)        

2          $(‘li.trigger’).click(handlerFn);
              

 

3           
                       

4          //
better: event delegation with $.fn.live            

 

5          $(‘li.trigger’).live(‘click’,
handlerFn);       

6           
                    

 

7          // best:
event delegation with $.fn.delegate         

8          // allows
you to specify a context easily                       

 

9          $(‘#myList’).delegate(‘li.trigger’,
‘click’, handlerFn);    

Detach Elements to Work With Them

The DOM is slow; you want to avoid manipulating it as
much as possible. jQuery introduced $.fn.detach in version 1.4 to help address
this issue, allowing you to remove an element from the DOM while you work with
it.

view sourceprint?

 

1          var
$table = $(‘#myTable’);                     

2          var
$parent = $table.parent();    

 

3           
                       

4          $table.detach();
            

 

5          // …
add lots and lots of rows to table    

6          $parent.append($table);                      

Use Stylesheets for Changing CSS on Many Elements

 If you’re changing
the CSS of more than 20 elements using $.fn.css, consider adding a style tag to
the page instead for a nearly 60% increase in speed.

 

 

 

 

 

 

 

 

 

 

 

 

             

Now what is NaN. NaN states for Not a Number. It’s a
value which a variable of type Number can hold meaning that it holds something
which is not a number. This is how you can get NaN:

 

1

2

3          Number(
"hello" );

0/0;

Math.sqrt( -1 );

The only way you can check if your variable holds NaN is
isNaN() global function. You can’t say

 

1          something
== NaN;     

because comparing to NaN always results in false. Even

 

1          NaN ==
NaN   

is false.

There’s another value for Numbers you should know —
Infinity. You can get it if you divide something by 0.

OK, let’s do our final test.

 

19        private
var undef: *;

trace( {}.x ); // undefined

trace( undef ); // undefined

trace( [][1] ); // undefined

trace( Number( "hello" ) ); // NaN

trace( 0/0 ); // NaN

trace( Math.sqrt( -1 ) ); // NaN

trace( 1/0 ); // Infinity

trace( NaN == undefined ); // false

trace( NaN === undefined ); // false

trace( null == undefined ); // true

trace( null === undefined ); // false

trace( NaN == NaN ); // false

trace( NaN === NaN ); // false

trace( null == null ); // true

trace( null === null ); // true

trace( undefined == undefined ); // true

trace( undefined === undefined ); // true        

 

////////////////////////////////////////////////////////////////////////////////////

Welcome

jQuery is fast becoming a must-have skill for front-end
developers. The purpose of this book is to provide an overview of the jQuery
JavaScript library; when you’re done with the book, you should be able to
complete basic tasks using jQuery, and have a solid basis from which to
continue your learning. This book was designed as material to be used in a
classroom setting, but you may find it useful for individual study.

This is a hands-on class. We will spend a bit of time
covering a concept, and then you’ll have the chance to work on an exercise
related to the concept. Some of the exercises may seem trivial; others may be
downright daunting. In either case, there is no grade; the goal is simply to
get you comfortable working your way through problems you’ll commonly be called
upon to solve using jQuery. Example solutions to all of the exercises are
included in the sample code.

Getting the Code

The code we’ll be using in this book is hosted in a
repository on Github . You can download a .zip or .tar file of the code, then
uncompress it to use it on your server. If you’re git-inclined, you’re welcome
to clone or fork the repository.

Software

You’ll want to have the following tools to make the most
of the class:

Adding JavaScript to Your Page

When you are writing JavaScript code, you can use the
following methods to send messages to the console:

·           console.log()
for sending general log messages

·           console.dir()
for logging a browseable object

·           console.warn()
for logging warnings

·           console.error()
for logging error messages

 

1          var foo =
‘hello world’;           

Example 2.2: Whitespace has no meaning outside of
quotation marks

view sourceprint?

 

1          var foo
=         ‘hello world’;   

Example 2.3: Parentheses indicate precedence

view sourceprint?

 

1          2 * 3 +
5;    // returns 11; multiplication happens first    

2          2 * (3 +
5);  // returns 16; addition happens first                     

Example 2.4: Tabs enhance readability, but have no
special meaning

view sourceprint?

 

1          var foo =
function() {                 

2              console.log(‘hello’);
 

 

3          };        

Operators

Basic Operators

3          var j =
++i;  // pre-increment:  j equals 2; i equals 2        

4          var k =
i++;  // post-increment: k equals 2; i equals 3  

Operations on Numbers & Strings

In JavaScript, numbers and strings will occasionally
behave in ways you might not expect.

1          var foo =
1;                     

2          var bar =
‘2’;      

4          console.log(foo
+ bar);  // 12. uh oh   

5          console.log(foo
+ Number(bar));        

The Number constructor, when called as a function (like above)
will have the effect of casting its argument into a number. You could also use
the unary plus operator, which does the same thing:

Example 2.10: Forcing a string to act as a number (using
the unary-plus operator)

view sourceprint?

 

1          console.log(foo
+ +bar);         

Logical Operators

Truthy and Falsy Things

In order to use flow control successfully, it’s important
to understand which kinds of values are "truthy" and which kinds of
values are "falsy." Sometimes, values that seem like they should
evaluate one way actually evaluate another.

1          ‘0’;                       

2          ‘any
string’;       

 

3          []; 
// an empty array                   

4          {}; 
// an empty object  

 

5          1;  
// any non-zero number    

Example 2.15: Values that evaluate to false

view sourceprint?

 

1          0;                        

2          ”; 
// an empty string      

3          NaN; //
JavaScript’s "not-a-number" variable      

4          null;                  

5          undefined; 
// be careful — undefined can be redefined!        

Conditional Variable Assignment with The Ternary Operator

Sometimes you want to set a variable to a value depending
on some condition. You could use an if/else statement, but in many cases the
ternary operator is more convenient. [Definition: The ternary operator tests a
condition; if the condition is true, it returns a certain value, otherwise it
returns a different value.]

Example 2.16: The ternary operator

view sourceprint?

 

1          // set
foo to 1 if bar is true;         

2          //
otherwise, set foo to 0                       

 

3          var foo =
bar ? 1 : 0;   

While the ternary operator can be used without assigning the
return value to a variable, this is generally discouraged.

Switch Statements

Rather than using a series of if/else if/else blocks,
sometimes it can be useful to use a switch statement instead. [Definition:
Switch statements look at the value of a variable or expression, and run
different blocks of code depending on the value.]

Example 2.17: A switch statement

view sourceprint?

 

01        switch
(foo) {    

03            case
‘bar’:                    

04                alert(‘the
value was bar — yay!’);  

05            break;
            

07            case
‘baz’:                   

08                alert(‘boo
baz :(‘);              

09            break;
            

11            default:
                      

12                alert(‘everything
else is just ok’);  

13            break;
            

15        }         

Switch statements have somewhat fallen out of favor in
JavaScript, because often the same behavior can be accomplished by creating an
object that has more potential for reuse, testing, etc. For example:

/////////////

In JavaScript, as in most object-oriented programming
languages, this is a special keyword that is used within methods to refer to
the object on which a method is being invoked. The value of this is determined
using a simple series of steps:

1.         If the
function is invoked using Function.call 
or Function.apply , this will be set to the first argument passed to
call/apply. If the first argument passed to call/apply is null or undefined,
this will refer to the global object (which is the window object in Web
browsers).

2.         If the
function being invoked was created using Function.bind , this will be the first
argument that was passed to bind at the time the function was created.

3.         If the
function is being invoked as a method of an object, this will refer to that
object.

4.         Otherwise,
the function is being invoked as a standalone function not attached to any
object, and this will refer to the global object.

 

Note

Closures

Closures are an extension of the concept of scope —
functions have access to variables that were available in the scope where the function
was created. If that’s confusing, don’t worry: closures are generally best
understood by example.

In “Functions can "see" changes in variable
values after the function is defined”, we saw how functions have access to
changing variable values. The same sort of behavior exists with functions
defined within loops — the function "sees" the change in the
variable’s value even after the function is defined, resulting in all clicks
alerting 5.

 

1          /* this
won’t behave as we want it to; */             

2          /* every
click will alert 5 */                

 

3          for (var
i=0; i<5; i++) {                           

4              $(‘<p>click
me</p>’).appendTo(‘body’).click(function() {    

 

5                  alert(i);
       

6              });
                

 

7          }         

Example 2.50: Locking in the value of i with a closure

view sourceprint?

 

1          /* fix:
“close” the value of i inside createFunction, so it won’t change */          

2          var
createFunction = function(i) {                     

 

3              return
function() { alert(i); };              

4          };                      

 

5           
                        

6          for (var
i=0; i<5; i++) {             

 

7              $(‘<p>click
me</p>’).appendTo(‘body’).click(createFunction(i));        

8          }                     

Closures can also be used to resolve issues with the this
keyword, which is unique to each scope:

Example 2.51: Using a closure to access inner and outer
object instances simultaneously

view sourceprint?

 

01        var
outerObj = {                          

02            myName
: ‘outer’,     

03            outerFunction
: function () {               

06                var
self = this;                   

08                var
innerObj = {    

09                    myName
: ‘inner’,                       

10                    innerFunction
: function () {     

11                        console.log(self.myName,
this.myName); // logs ‘outer inner’            

12                    }
                      

13                };
               

15                innerObj.innerFunction();
              

17                console.log(this.myName);
// logs ‘outer’                

18            }
                  

19        };            

21        outerObj.outerFunction();       

This mechanism can be particularly useful when dealing
with callbacks, though in those cases, it is often better to use Function.bind
, which will avoid any overhead associated with scope traversal.

 

/////////////////

 

Choosing Selectors

Choosing good selectors is one way to improve the
performance of your JavaScript. A little specificity — for example, including
an element type such as div when selecting elements by class name — can go a
long way. Generally, any time you can give jQuery a hint about where it might
expect to find what you’re looking for, you should. On the other hand, too much
specificity can be a bad thing. A selector such as #myTable thead tr th.special
is overkill if a selector such as #myTable th.special will get you what you
want.

jQuery offers many attribute-based selectors, allowing
you to make selections based on the content of arbitrary attributes using
simplified regular expressions.

view sourceprint?

 

1          // find
all <a>s whose rel attribute           

2          // ends
with "thinger"                

 

3          $("a[rel$=’thinger’]");  

While these can be useful in a pinch, they can also be
extremely slow — I once wrote an attribute-based selector that locked up my
page for multiple seconds. Wherever possible, make your selections using IDs,
class names, and tag names.

Want to know more? Paul Irish has a great presentation
about improving performance in JavaScript , with several slides focused
specifically on selector performance.

Does My Selection Contain Any Elements?

Once you’ve made a selection, you’ll often want to know
whether you have anything to work with. You may be inclined to try something
like:

view sourceprint?

 

1          if
($(‘div.foo’)) { … }  

This won’t work. When you make a selection using $(), an
object is always returned, and objects always evaluate to true. Even if your
selection doesn’t contain any elements, the code inside the if statement will
still run.

Instead, you need to test the selection’s length
property, which tells you how many elements were selected. If the answer is 0,
the length property will evaluate to false when used as a boolean value.

Example 3.9: Testing whether a selection contains
elements

view sourceprint?

 

1          if
($(‘div.foo’).length) { … }    

Refining & Filtering Selections

Sometimes you have a selection that contains more than
what you’re after; in this case, you may want to refine your selection. jQuery
offers several methods for zeroing in on exactly what you’re after.

Example 3.11: Refining selections

view sourceprint?

 

1          $(‘div.foo’).has(‘p’);         
// div.foo elements that contain <p>’s                         

2          $(‘h1’).not(‘.bar’);           
// h1 elements that don’t have a class of bar  

 

3          $(‘ul
li’).filter(‘.current’);  // unordered list items with class of current    

4          $(‘ul li’).first();            
// just the first unordered list item                      

 

5          $(‘ul
li’).eq(5);              
// the sixth      

Selecting Form Elements

jQuery offers several pseudo-selectors that help you find
elements in your forms; these are especially helpful because it can be
difficult to distinguish between form elements based on their state or type
using standard CSS selectors.

:button

Selects <button> elements and elements with
type="button"

:checkbox

Selects inputs with type="checkbox"

:checked

Selects checked inputs

:disabled

Selects disabled form elements

:enabled

Selects enabled form elements

:file

Selects inputs with type="file"

:image

Selects inputs with type="image"

:input

Selects <input>, <textarea>, and
<select> elements

:password

Selects inputs with type="password"

:radio

Selects inputs with type="radio"

:reset

Selects inputs with type="reset"

:selected

Selects options that are selected

:submit

Selects inputs with type="submit"

:text

Selects inputs with type="text"

Example 3.12: Using form-related pseduo-selectors

view sourceprint?

 

1          $(‘#myForm
:input’); // get all elements that accept input        

Chaining

If you call a method on a selection and that method
returns a jQuery object, you can continue to call jQuery methods on the object
without pausing for a semicolon.

Example 3.13: Chaining

view sourceprint?

 

1          $(‘#content’).find(‘h3’).eq(2).html(‘new
text for the third h3!’);           

If you are writing a chain that includes several steps,
you (and the person who comes after you) may find your code more readable if
you break the chain over several lines.

Example 3.14: Formatting chained code

view sourceprint?

 

1          $(‘#content’)
                   

2              .find(‘h3’)
     

 

3              .eq(2)
                         

4              .html(‘new
text for the third h3!’);   

If you change your selection in the midst of a chain,
jQuery provides the $.fn.end method to get you back to your original selection.

Example 3.15: Restoring your original selection using
$.fn.end

view sourceprint?

 

1          $(‘#content’)
                   

2              .find(‘h3’)
     

 

3              .eq(2)
                         

4                  .html(‘new
text for the third h3!’)              

 

5              .end()
// restores the selection to all h3’s in #content               

6              .eq(0)
                       

 

7                  .html(‘new
text for the first h3!’);

Note

Chaining is extraordinarily powerful, and it’s a feature
that many libraries have adapted since it was made popular by jQuery. However,
it must be used with care. Extensive chaining can make code extremely difficult
to modify or debug. There is no hard-and-fast rule to how long a chain should
be — just know that it is easy to get carried away.

Getters & Setters

Example 3.16: The $.fn.html method used as a setter

view sourceprint?

 

1          $(‘h1’).html(‘hello
world’);      

Example 3.17: The html method used as a getter

view sourceprint?

 

1          $(‘h1’).html();  

Setters return a jQuery object, allowing you to continue
to call jQuery methods on your selection; getters return whatever they were
asked to get, meaning you cannot continue to call jQuery methods on the value
returned by the getter.

CSS, Styling, & Dimensions

jQuery includes a handy way to get and set CSS properties
of elements.

Note

            CSS
properties that normally include a hyphen need to be camel cased in JavaScript.
For example, the CSS property font-size is expressed as fontSize when used as a
property name in JavaScript. This does not apply, however, when passing the
name of a CSS property to the $.fn.css method as a string — in that case,
either the camel cased or hyphenated form will work.

 

1          $(‘h1’).css(‘fontSize’);
// returns a string such as "19px"              

2          $(‘h1’).css(‘font-size’);
// also works                

Example 3.19: Setting CSS properties

view sourceprint?

 

1          $(‘h1’).css(‘fontSize’,
‘100px’); // setting an individual property                          

2          $(‘h1’).css({
‘fontSize’ : ‘100px’, ‘color’ : ‘red’ }); // setting multiple properties

Note the style of the argument we use on the second line
— it is an object that contains multiple properties. This is a common way to
pass multiple arguments to a function, and many jQuery setter methods accept
objects to set mulitple values at once.

Using CSS Classes for Styling

As a getter, the $.fn.css method is valuable; however, it
should generally be avoided as a setter in production-ready code, because you
don’t want presentational information in your JavaScript. Instead, write CSS
rules for classes that describe the various visual states, and then simply
change the class on the element you want to affect.

Example 3.20: Working with classes

view sourceprint?

 

1          var $h1 =
$(‘h1’);            

2                                 

 

3          $h1.addClass(‘big’);
                   

4          $h1.removeClass(‘big’);
           

 

5          $h1.toggleClass(‘big’);
   

6           
                     

 

7          if
($h1.hasClass(‘big’)) { … }  

Classes can also be useful for storing state information
about an element, such as indicating that an element is selected.

Dimensions

jQuery offers a variety of methods for obtaining and
modifying dimension and position information about an element.

The code in “Basic dimensions methods”, is just a very
brief overview of the dimensions functionality in jQuery; for complete details
about jQuery dimension methods, visit http://api.jquery.com/category/dimensions/
.

Example 3.21: Basic dimensions methods

view sourceprint?

 

1          $(‘h1′).width(’50px’);  
// sets the width of all H1 elements         

2          $(‘h1’).width();        
// gets the width of the first H1                 

 

3           
                        

4          $(‘h1′).height(’50px’); 
// sets the height of all H1 elements       

 

5          $(‘h1’).height();       
// gets the height of the first H1       

6           
                     

 

7          $(‘h1’).position();     
// returns an object containing position                  

8                                   //
information for the first H1 relative to          

 

9                                   //
its "offset (positioned) parent"        

Attributes

 

view sourceprint?

 

1          $(‘h1’).next(‘p’);
                         

2          $(‘div:visible’).parent();
            

 

3          $(‘input[name=first_name]’).closest(‘form’);
      

4          $(‘#myList’).children();
                        

 

5          $(‘li.selected’).siblings();         

 

$.fn.html

Get or set the html contents.

$.fn.text

Get or set the text contents; HTML will be stripped.

$.fn.position

Get an object with position information for the first
element in the selection, relative to its first positioned ancestor. This is a
getter only.

Moving, Copying, and Removing Elements

There are a variety of ways to move elements around the
DOM; generally, there are two approaches:

·           Place
the selected element(s) relative to another element

·           Place an
element relative to the selected element(s)

 

1          // make
the first list item the last list item                        

2          var $li =
$(‘#myList li:first’).appendTo(‘#myList’);        

4          //
another approach to the same problem          

5          $(‘#myList’).append($(‘#myList
li:first’));           

7          // note
that there’s no way to access the                          

8          // list
item that we moved, as this returns          

9          // the
list itself 

Cloning Elements

When you use methods such as $.fn.appendTo, you are
moving the element; sometimes you want to make a copy of the element instead.
In this case, you’ll need to use $.fn.clone first.

Example 3.28: Making a copy of an element

view sourceprint?

 

1          // copy
the first list item to the end of the list      

2          $(‘#myList
li:first’).clone().appendTo(‘#myList’);        

If you need to copy related data and events, be sure to
pass true as an argument to $.fn.clone.

Removing Elements

There are two ways to remove elements from the page:
$.fn.remove and $.fn.detach. You’ll use $.fn.remove when you want to
permanently remove the selection from the page; while the method does return the
removed element(s), those elements will not have their associated data and
events attached to them if you return them to the page.

If you need the data and events to persist, you’ll want
to use $.fn.detach instead. Like $.fn.remove, it returns the selection, but it
also maintains the data and events associated with the selection, so you can
restore the selection to the page at a later time.

Note

The $.fn.detach method is extremely valuable if you are doing
heavy manipulation to an element. In that case, it’s beneficial to $.fn.detach
the element from the page, work on it in your code, and then restore it to the
page when you’re done. This saves you from expensive "DOM touches"
while maintaining the element’s data and events.

If you want to leave the element on the page but simply
want to remove its contents, you can use $.fn.empty to dispose of the element’s
inner HTML.

Creating New Elements

jQuery offers a trivial and elegant way to create new
elements using the same $() method you use to make selections.

Example 3.29: Creating new elements

view sourceprint?

 

1          $(‘<p>This
is a new paragraph</p>’);                  

2          $(‘<li
class="new">new list item</li>’);           

Example 3.30: Creating a new element with an attribute
object

view sourceprint?

 

1          $(‘<a/>’,
{                        

2              html
: ‘This is a <strong>new</strong> link’,             

 

3              ‘class’
: ‘new’,                          

4              href
: ‘foo.html’       

 

5          });       

Note that in the attributes object we included as the
second argument, the property name class is quoted, while the property names
text and href are not. Property names generally do not need to be quoted unless
they are reserved words (as class is in this case).

When you create a new element, it is not immediately
added to the page. There are several ways to add an element to the page once
it’s been created.

Example 3.31: Getting a new element on to the page

view sourceprint?

 

1          var
$myNewElement = $(‘<p>New element</p>’);          

2          $myNewElement.appendTo(‘#content’);
                      

 

3           
                        

4          $myNewElement.insertAfter(‘ul:last’);
// this will remove the p from #content!            

 

5          $(‘ul’).last().after($myNewElement.clone()); 
// clone the p so now we have 2           

Strictly speaking, you don’t have to store the created element
in a variable — you could just call the method to add the element to the page
directly after the $(). However, most of the time you will want a reference to
the element you added, so you don’t need to select it later.

You can even create an element as you’re adding it to the
page, but note that in this case you don’t get a reference to the newly created
element.

Example 3.32: Creating and adding an element to the page
at the same time

view sourceprint?

 

1          $(‘ul’).append(‘<li>list
item</li>’);       

Note

The syntax for adding new elements to the page is so
easy, it’s tempting to forget that there’s a huge performance cost for adding
to the DOM repeatedly. If you are adding many elements to the same container,
you’ll want to concatenate all the html into a single string, and then append
that string to the container instead of appending the elements one at a time.
You can use an array to gather all the pieces together, then join them into a
single string for appending.

view sourceprint?

 

1          var
myItems = [], $myList = $(‘#myList’);           

2                                 

 

3          for (var
i=0; i<100; i++) {                       

4              myItems.push(‘<li>item
‘ + i + ‘</li>’);           

 

5          }                         

6           
         

 

7          $myList.append(myItems.join(”));      

Manipulating Attributes

jQuery’s attribute manipulation capabilities are
extensive. Basic changes are simple, but the $.fn.attr method also allows for
more complex manipulations. It can either set an explicit value, or set a value
using the return value of a function. When the function syntax is used, the
function receives two arguments: the zero-based index of the element whose
attribute is being changed, and the current value of the attribute being
changed.

Example 3.33: Manipulating a single attribute

view sourceprint?

 

1          $(‘#myDiv
a:first’).attr(‘href’, ‘newDestination.html’); 

Example 3.34: Manipulating multiple attributes

view sourceprint?

 

1          $(‘#myDiv
a:first’).attr({                         

2              href
: ‘newDestination.html’,             

 

3              rel
: ‘super-special’     

4          });                   

Example 3.35: Using a function to determine an
attribute’s new value

view sourceprint?

 

01        $(‘#myDiv
a:first’).attr({             

02            rel
: ‘super-special’,  

 

03            href
: function(idx, href) {      

04                return
‘/new/’ + href;                     

 

05            }
        

06        });                     

 

07         
                        

08        $(‘#myDiv
a:first’).attr(‘href’, function(idx, href) {       

 

09            return
‘/new/’ + href;               

10        });                   

Exercises

Selecting

Open the file /exercises/index.html in your browser. Use the
file /exercises/js/sandbox.js or work in Firebug to accomplish the following:

1.         Select
all of the div elements that have a class of "module".

2.         Come up
with three selectors that you could use to get the third item in the #myList
unordered list. Which is the best to use? Why?

3.         Select
the label for the search input using an attribute selector.

4.         Figure
out how many elements on the page are hidden (hint: .length).

5.         Figure
out how many image elements on the page have an alt attribute.

6.         Select
all of the odd table rows in the table body.

Traversing

Open the file /exercises/index.html in your browser. Use
the file /exercises/js/sandbox.js or work in Firebug to accomplish the
following:

1.         Select
all of the image elements on the page; log each image’s alt attribute.

2.         Select
the search input text box, then traverse up to the form and add a class to the
form.

3.         Select
the list item inside #myList that has a class of "current" and remove
that class from it; add a class of "current" to the next list item.

4.         Select
the select element inside #specials; traverse your way to the submit button.

5.         Select
the first list item in the #slideshow element; add the class
"current" to it, and then add a class of "disabled" to its
sibling elements.

Manipulating

Open the file /exercises/index.html in your browser. Use
the file /exercises/js/sandbox.js or work in Firebug to accomplish the
following:

1.         Add five
new list items to the end of the unordered list #myList. Hint:

view sourceprint?

 

1          for (var i
= 0; i<5; i++) { … }  

2.         Remove
the odd list items

3.         Add
another h2 and another paragraph to the last div.module

4.         Add
another option to the select element; give the option the value
"Wednesday"

5.         Add a new
div.module to the page after the last one; put a copy of one of the existing
images inside of it.

Back to top

jQuery Core

$ vs $()

Until now, we’ve been dealing entirely with methods that
are called on a jQuery object. For example:

view sourceprint?

 

1          $(‘h1’).remove();         

Most jQuery methods are called on jQuery objects as shown
above; these methods are said to be part of the $.fn namespace, or the “jQuery
prototype,” and are best thought of as jQuery object methods.

However, there are several methods that do not act on a selection;
these methods are said to be part of the jQuery namespace, and are best thought
of as core jQuery methods.

This distinction can be incredibly confusing to new
jQuery users. Here’s what you need to remember:

·           Methods
called on jQuery selections are in the $.fn namespace, and automatically
receive and return the selection as this.

·           Methods
in the $ namespace are generally utility-type methods, and do not work with
selections; they are not automatically passed any arguments, and their return
value will vary.

There are a few cases where object methods and core
methods have the same names, such as $.each and $.fn.each. In these cases, be
extremely careful when reading the documentation that you are exploring the
correct method.

Utility Methods

jQuery offers several utility methods in the $ namespace.
These methods are helpful for accomplishing routine programming tasks. Below
are examples of a few of the utility methods; for a complete reference on
jQuery utility methods, visit http://api.jquery.com/category/utilities/
.

$.trim

Removes leading and trailing whitespace.

view sourceprint?

 

1          $.trim(‘   
lots of extra whitespace    ‘);                

2          //
returns ‘lots of extra whitespace’                  

$.each

Iterates over arrays and objects.

view sourceprint?

 

1          $.each([
‘foo’, ‘bar’, ‘baz’ ], function(idx, val) {              

2              console.log(‘element
‘ + idx + ‘is ‘ + val);                  

 

3          });           

4           
                    

 

5          $.each({
foo : ‘bar’, baz : ‘bim’ }, function(k, v) {           

6              console.log(k
+ ‘ : ‘ + v);                   

 

7          });       

Note

There is also a method $.fn.each, which is used for
iterating over a selection of elements.

$.inArray

Returns a value’s index in an array, or -1 if the value
is not in the array.

view sourceprint?

 

1          var
myArray = [ 1, 2, 3, 5 ];        

2                                 

 

3          if
($.inArray(4, myArray) !== -1) {        

4              console.log(‘found
it!’);                     

 

5          }         

$.extend

Changes the properties of the first object using the
properties of subsequent objects.

view sourceprint?

 

1          var
firstObject = { foo : ‘bar’, a : ‘b’ };    

2          var
secondObject = { foo : ‘baz’ };                    

 

3           
                       

4          var
newObject = $.extend(firstObject, secondObject);              

 

5          console.log(firstObject.foo);
// ‘baz’        

6          console.log(newObject.foo);  
// ‘baz’  

If you don’t want to change any of the objects you pass
to $.extend, pass an empty object as the first argument.

view sourceprint?

 

1          var
firstObject = { foo : ‘bar’, a : ‘b’ };    

2          var
secondObject = { foo : ‘baz’ };                    

 

3           
                       

4          var
newObject = $.extend({}, firstObject, secondObject);        

 

5          console.log(firstObject.foo);
// ‘bar’        

6          console.log(newObject.foo);  
// ‘baz’  

$.proxy

Returns a function that will always run in the provided
scope — that is, sets the meaning of this inside the passed function to the
second argument.

view sourceprint?

 

1          var
myFunction = function() { console.log(this); };        

2          var
myObject = { foo : ‘bar’ };                          

 

3           
                       

4          myFunction();
// logs window object     

 

5           
                       

6          var
myProxyFunction = $.proxy(myFunction, myObject);       

 

7          myProxyFunction();
// logs myObject object   

If you have an object with methods, you can pass the
object and the name of a method to return a function that will always run in
the scope of the object.

view sourceprint?

 

1          var
myObject = {                        

2              myFn
: function() {  

 

3                  console.log(this);
               

4              }
                  

 

5          };            

6           
                    

 

7          $(‘#foo’).click(myObject.myFn);
// logs DOM element #foo                   

8          $(‘#foo’).click($.proxy(myObject,
‘myFn’)); // logs myObject 

Checking types

As mentioned in the "JavaScript basics"
section, jQuery offers a few basic utility methods for determining the type of
a specific value.

Example 4.1: Checking the type of an arbitrary value

view sourceprint?

 

01        var
myValue = [1, 2, 3];             

02                               

 

03        // Using
JavaScript’s typeof operator to test for primative types              

04        typeof
myValue == ‘string’; // false                   

 

05        typeof
myValue == ‘number’; // false                  

06        typeof
myValue == ‘undefined’; // false            

 

07        typeof
myValue == ‘boolean’; // false    

08         
                     

 

09        // Using
strict equality operator to check for null            

10        myValue
=== null; // false                    

 

11         
                        

12        // Using
jQuery’s methods to check for non-primative types     

 

13        jQuery.isFunction(myValue);
// false                  

14        jQuery.isPlainObject(myValue);
// false            

 

15        jQuery.isArray(myValue);
// true        

Data Methods

As your work with jQuery progresses, you’ll find that
there’s often data about an element that you want to store with the element. In
plain JavaScript, you might do this by adding a property to the DOM element,
but you’d have to deal with memory leaks in some browsers. jQuery offers a
straightforward way to store data related to an element, and it manages the
memory issues for you.

Example 4.2: Storing and retrieving data related to an
element

view sourceprint?

 

1          $(‘#myDiv’).data(‘keyName’,
{ foo : ‘bar’ });                  

2          $(‘#myDiv’).data(‘keyName’);
// { foo : ‘bar’ }

You can store any kind of data on an element, and it’s
hard to overstate the importance of this when you get into complex application
development. For the purposes of this class, we’ll mostly use $.fn.data to
store references to other elements.

For example, we may want to establish a relationship
between a list item and a div that’s inside of it. We could establish this
relationship every single time we interact with the list item, but a better
solution would be to establish the relationship once, and then store a pointer
to the div on the list item using $.fn.data:

Example 4.3: Storing a relationship between elements
using $.fn.data

view sourceprint?

 

1          $(‘#myList
li’).each(function() {                         

2              var
$li = $(this), $div = $li.find(‘div.content’);          

 

3              $li.data(‘contentDiv’,
$div);                

4          });                     

 

5           
                        

6          // later,
we don’t have to find the div again;      

 

7          // we can
just read it from the list item’s data      

8          var
$firstLi = $(‘#myList li:first’);                      

 

9          $firstLi.data(‘contentDiv’).html(‘new
content’);           

In addition to passing $.fn.data a single key-value pair
to store data, you can also pass an object containing one or more pairs.

Avoiding Conflicts with Other Libraries

 

 

3          <script>var
$j = jQuery.noConflict();</script>

You can continue to use the standard $ by wrapping your
code in a self-executing anonymous function; this is a standard pattern for
plugin authoring, where the author cannot know whether another library will
have taken over the $.

Example 4.5: Using the $ inside a self-executing anonymous
function

view sourceprint?

 

1          <script
src="prototype.js"></script>        

2          <script
src="jquery.js"></script>                       

 

3          <script>
                          

4          jQuery.noConflict();
    

 

5           
                        

6          (function($)
{  

 

7             //
your code here, using the $               

8          })(jQuery);
                   

 

9          </script>          

 

Events

Overview

 

Connecting Events to Run Only Once

Sometimes you need a particular handler to run only once
— after that, you may want no handler to run, or you may want a different handler
to run. jQuery provides the $.fn.one method for this purpose.

 

1          $(‘p’).one(‘click’,
function() {                  

2              console.log(‘You
just clicked this for the first time!’);           

 

3              $(this).click(function()
{ console.log(‘You have clicked this before!’); });      

4          });                   

Binding Multiple Events

Quite often elements in your application will be bound to
multiple events, each having a different function for handing the event. In
these cases you can pass an object into $.fn.bind with one or more key/value
pairs, with the key being the event name and the value being the function to
handle the event.

Example 5.8: Binding Multiple Events

view sourceprint?

 

1          $(‘p’).bind({
                   

2              ‘click’:
function() { console.log(‘clicked!’); },            

 

3              ‘mouseover’:
function() { console.log(‘hovered!’); }               

4          });                   

Note

The option to pass an object of multiple events and
handlers to $.fn.bind was introduced in jQuery 1.4.4.

Inside the Event Handling Function

As mentioned in the overview, the event handling function
receives an event object, which contains many properties and methods. The event
object is most commonly used to prevent the default action of the event via the
preventDefault method. However, the event object contains a number of other
useful properties and methods, including:

pageX, pageY

The mouse position at the time the event occurred,
relative to the top left of the page.

type

The type of the event (e.g. "click").

which

The button or key that was pressed.

data

Any data that was passed in when the event was bound.

target

The DOM element that initiated the event.

preventDefault()

Prevent the default action of the event (e.g. following a
link).

stopPropagation()

Stop the event from bubbling up to other elements.

In addition to the event object, the event handling
function also has access to the DOM element that the handler was bound to via
the keyword this. To turn the DOM element into a jQuery object that we can use
jQuery methods on, we simply do $(this), often following this idiom:

view sourceprint?

 

1          var $this
= $(this);       

Preventing a link from being followed

view sourceprint?

 

1          $(‘a’).click(function(e)
{             

2              var
$this = $(this);                 

 

3              if
($this.attr(‘href’).match(‘evil’)) {      

4                  e.preventDefault();
                      

 

5                  $this.addClass(‘evil’);
         

6              }
                  

 

7          });       

Triggering Event Handlers

jQuery provides a way to trigger the event handlers bound
to an element without any user interaction via the $.fn.trigger method. While
this method has its uses, it should not be used simply to call a function that
was bound as a click handler. Instead, you should store the function you want
to call in a variable, and pass the variable name when you do your binding.
Then, you can call the function itself whenever you want, without the need for
$.fn.trigger.

Triggering an event handler the right way

view sourceprint?

 

01        var foo =
function(e) {               

02            if
(e) {                       

 

03                console.log(e);
       

04            }
else {                      

 

05                console.log(‘this
didn\’t come from an event!’);      

06            }
                  

 

07        };            

08         
                     

 

09         
                        

10        $(‘p’).click(foo);
           

 

11         
                        

12        foo(); //
instead of $(‘p’).trigger(‘click’)           

$.fn.hover

The $.fn.hover method lets you pass one or two functions
to be run when the mouseenter and mouseleave events occur on an element. If you
pass one function, it will be run for both events; if you pass two functions,
the first will run for mouseenter, and the second will run for mouseleave.

Note

Prior to jQuery 1.4, the $.fn.hover method required two
functions.

The hover helper function

view sourceprint?

 

1          $(‘#menu
li’).hover(function() {                          

2              $(this).toggleClass(‘hover’);
 

 

3          });       

$.fn.toggle

The $.fn.toggle method is triggered by the "click"
event and accepts two or more functions. Each time the click event occurs, the
next function in the list is called. Generally, $.fn.toggle is used with just
two functions; however, it will accept an unlimited number of functions. Be
careful, though: providing a long list of functions can be difficult to debug).

The toggle helper function

view sourceprint?

 

1          $(‘p.expander’).toggle(
               

2              function()
{               

 

3                  $(this).prev().addClass(‘open’);
      

4              },
                 

 

5              function()
{                 

6                  $(this).prev().removeClass(‘open’);
          

 

7              }
        

8          );                     

Exercises

Create an Input Hint

Open the file /exercises/index.html in your browser. Use
the file /exercises/js/inputHint.js or work in Firebug. Your task is to use the
text of the label for the search input to create "hint" text for the
search input. The steps are as follows:

1.         Set the
value of the search input to the text of the label element

2.         Add a
class of "hint" to the search input

3.         Remove
the label element

4.         Bind a focus
event to the search input that removes the hint text and the "hint"
class

5.         Bind a
blur event to the search input that restores the hint text and "hint"
class if no search text was entered

What other considerations might there be if you were
creating this functionality for a real site?

Add Tabbed Navigation

Open the file /exercises/index.html in your browser. Use
the file /exercises/js/tabs.js. Your task is to create tabbed navigation for
the two div.module elements. To accomplish this:

1.         Hide all
of the modules.

2.         Create an
unordered list element before the first module.

3.         Iterate
over the modules using $.fn.each. For each module, use the text of the h2
element as the text for a list item that you add to the unordered list element.

4.         Bind a
click event to the list item that:

o          Shows the
related module, and hides any other modules

o          Adds a
class of "current" to the clicked list item

o          Removes
the class "current" from the other list item

5.         Finally,
show the first tab.

Back to top

Effects

Overview

jQuery makes it trivial to add simple effects to your
page. Effects can use the built-in settings, or provide a customized duration.
You can also create custom animations of arbitrary CSS properties.

For complete details on jQuery effects, visit http://api.jquery.com/category/effects/
.

Built-in Effects

Frequently used effects are built into jQuery as methods:

$.fn.show

Show the selected element.

$.fn.hide

Hide the selected elements.

$.fn.fadeIn

Animate the opacity of the selected elements to 100%.

$.fn.fadeOut

Animate the opacity of the selected elements to 0%.

$.fn.slideDown

Display the selected elements with a vertical sliding
motion.

$.fn.slideUp

Hide the selected elements with a vertical sliding
motion.

$.fn.slideToggle

Show or hide the selected elements with a vertical
sliding motion, depending on whether the elements are currently visible.

Example 6.1: A basic use of a built-in effect

Custom Effects with $.fn.animate

jQuery makes it possible to animate arbitrary CSS
properties via the $.fn.animate method. The $.fn.animate method lets you
animate to a set value, or to a value relative to the current value.

Example 6.6: Custom effects with $.fn.animate

view sourceprint?

 

1          $(‘div.funtimes’).animate(
          

2              {
                  

 

3                  left
: "+=50",           

4                  opacity
: 0.25        

 

5              },
                   

6              300,
// duration         

 

7              function()
{ console.log(‘done!’); // calback                

8          });                   

Note

Color-related properties cannot be animated with
$.fn.animate using jQuery out of the box. Color animations can easily be
accomplished by including the color plugin . We’ll discuss using plugins later
in the book.

Easing

[Definition: Easing describes the manner in which an
effect occurs — whether the rate of change is steady, or varies over the
duration of the animation.] jQuery includes only two methods of easing: swing
and linear. If you want more natural transitions in your animations, various
easing plugins are available.

As of jQuery 1.4, it is possible to do per-property
easing when using the $.fn.animate method.

Example 6.7: Per-property easing

view sourceprint?

 

1          $(‘div.funtimes’).animate(
          

2              {
                  

 

3                  left
: [ "+=50", "swing" ],                            

4                  opacity
: [ 0.25, "linear" ]             

 

5              },
                   

6              300
 

 

7          );         

For more details on easing options, see http://api.jquery.com/animate/ .

Managing Effects

jQuery provides several tools for managing animations.

$.fn.stop

Stop currently running animations on the selected
elements.

$.fn.delay

Wait the specified number of milliseconds before running
the next animation.

view sourceprint?

 

1          $(‘h1’).show(300).delay(1000).hide(300);      

jQuery.fx.off

If this value is true, there will be no transition for
animations; elements will immediately be set to the target final state instead.
This can be especially useful when dealing with older browsers; you also may
want to provide the option to your users.

 

Beware anonymous functions

Anonymous functions bound everywhere are a pain. They’re
difficult to debug, maintain, test, or reuse. Instead, use an object literal to
organize and name your handlers and callbacks.

view sourceprint?

 

01        // BAD                            

02        $(document).ready(function()
{            

 

03            $(‘#magic’).click(function(e)
{                        

04                $(‘#yayeffects’).slideUp(function()
{        

 

05                    //
        

06                });
                        

 

07            });
      

08         
                    

 

09            $(‘#happiness’).load(url
+ ‘ #unicorns’, function() {                

10                //
                      

 

11            });
      

12        });                     

 

13         
                       

14        // BETTER        

 

15        var PI = {
                       

16            onReady
: function() {          

 

17                $(‘#magic’).click(PI.candyMtn);
                 

18                $(‘#happiness’).load(PI.url
+ ‘ #unicorns’, PI.unicornCb);             

 

19            },
       

20         
                    

 

21            candyMtn
: function(e) {                    

22                $(‘#yayeffects’).slideUp(PI.slideCb);
       

 

23            },
       

24         
                    

 

25            slideCb
: function() { … },      

26         
                    

 

27            unicornCb
: function() { … }              

28        };                      

 

29         
                       

30        $(document).ready(PI.onReady);        

Optimize Selectors

Selector optimization is less important than it used to
be, as more browsers implement document.querySelectorAll() and the burden of
selection shifts from jQuery to the browser. However, there are still some tips
to keep in mind.

ID-Based Selectors

Beginning your selector with an ID is always best.

view sourceprint?

 

1          // fast                  

2          $(‘#container
div.robotarm’);    

 

3           
                       

4          //
super-fast       

 

5          $(‘#container’).find(‘div.robotarm’);    

The $.fn.find approach is faster because the first
selection is handled without going through the Sizzle selector engine — ID-only
selections are handled using document.getElementById(), which is extremely fast
because it is native to the browser.

Specificity

Be specific on the right-hand side of your selector, and
less specific on the left.

view sourceprint?

 

1          //
unoptimized                 

2          $(‘div.data
.gonzalez’);              

 

3           
                       

4          //
optimized       

 

5          $(‘.data
td.gonzalez’);  

Use tag.class if possible on your right-most selector,
and just tag or just .class on the left.

Avoid excessive specificity.

view sourceprint?

 

1          $(‘.data
table.attendees td.gonzalez’);      

2                                 

 

3          //
better: drop the middle if possible       

4          $(‘.data
td.gonzalez’);              

A "flatter" DOM also helps improve selector
performance, as the selector engine has fewer layers to traverse when looking
for an element.

Avoid the Universal Selector

Selections that specify or imply that a match could be
found anywhere can be very slow.

view sourceprint?

 

1          $(‘.buttons
> *’);  // extremely expensive            

2          $(‘.buttons’).children(); 
// much better                          

 

3           
                       

4          $(‘.gender
:radio’);  // implied universal selection          

 

5          $(‘.gender
*:radio’); // same thing, explicit now               

6          $(‘.gender
input:radio’); // much better            

Use Event Delegation

Event delegation allows you to bind an event handler to
one container element (for example, an unordered list) instead of multiple
contained elements (for example, list items). jQuery makes this easy with
$.fn.live and $.fn.delegate. Where possible, you should use $.fn.delegate
instead of $.fn.live, as it eliminates the need for an unnecessary selection,
and its explicit context (vs. $.fn.live’s context of document) reduces overhead
by approximately 80%.

In addition to performance benefits, event delegation
also allows you to add new contained elements to your page without having to
re-bind the event handlers for them as they’re added.

view sourceprint?

 

1          // bad
(if there are lots of list items)        

2          $(‘li.trigger’).click(handlerFn);
              

 

3           
                       

4          //
better: event delegation with $.fn.live            

 

5          $(‘li.trigger’).live(‘click’,
handlerFn);       

6           
                    

 

7          // best:
event delegation with $.fn.delegate         

8          // allows
you to specify a context easily                       

 

9          $(‘#myList’).delegate(‘li.trigger’,
‘click’, handlerFn);    

Detach Elements to Work With Them

The DOM is slow; you want to avoid manipulating it as
much as possible. jQuery introduced $.fn.detach in version 1.4 to help address
this issue, allowing you to remove an element from the DOM while you work with
it.

view sourceprint?

 

1          var
$table = $(‘#myTable’);                     

2          var
$parent = $table.parent();    

 

3           
                       

4          $table.detach();
            

 

5          // …
add lots and lots of rows to table    

6          $parent.append($table);                      

Use $.data Instead of $.fn.data

Using $.data on a DOM element instead of calling $.fn.data
on a jQuery selection can be up to 10 times faster. Be sure you understand the
difference between a DOM element and a jQuery selection before doing this,
though.

view sourceprint?

 

1          //
regular                         

2          $(elem).data(key,value);

 

             

 

3           
                       

4          // 10x
faster      

 

5         

$.data(elem,key,value);          

Don’t Act on Absent Elements

 

08        if
($mySelection.length) { $mySelection.slideUp(); }  

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

2. The Find Selector

One such solution is to use the find() method, when
possible. The key is stray away from forcing jQuery to use its Sizzle engine,
if it’s not necessary. Certainly, there will be times when this isn’t possible
— and that’s okay; but, if you don’t require the extra overhead, don’t go
looking for it.

view plaincopy to clipboardprint?

// Fine in modern browsers, though Sizzle does begin
"running" 

$(‘#someDiv p.someClass’).hide(); 

// Better for all browsers, and Sizzle never inits. 

$(‘#someDiv’).find(‘p.someClass’).hide(); 

Utilize the find() method. This way, rather than using
Sizzle, we can continue using the browser’s native functions.

When using Sizzle, optimize the right-most part of your
selector as much as possible.

Context Instead?

It’s also possible to add a context to your selectors,
such as:

view plaincopy to clipboardprint?

$(‘.someElements’, ‘#someContainer’).hide(); 

This code directs jQuery to wrap a collection of all the
elements with a class of someElements — that are children of someContainer —
within jQuery. Using a context is a helpful way to limit DOM traversal, though,
behind the scenes, jQuery is using the find method instead.

view plaincopy to clipboardprint?

$(‘#someContainer’) 

  .find(‘.someElements’) 

  .hide(); 

Proof

view plaincopy to clipboardprint?

// HANDLE: $(expr, context) 

// (which is just equivalent to:
$(context).find(expr) 

} else { 

   return jQuery(
context ).find( selector ); 

} 

3. Don’t Abuse $(this)

Use chaining

    alert( this.id
); 

 

4. jQuery’s Shorthand Ready Method

Listening for when the document is ready to be
manipulated is laughably simple with jQuery.

view plaincopy to clipboardprint?

$(document).ready(function() { 

    // let’s get up
in heeya 

}); 

 

$(function() { 

    // let’s get up
in heeya 

}); 

Though the latter is somewhat less readable, the two
snippets above are identical.

5. Keep your Code Safe

If developing code for distribution, it’s always
important to compensate for any possible name clashing. What would happen if
some script, imported after yours, also had a $ function? Bad stuff!

The answer is to either call jQuery’s noConflict(), or to
store your code within a self-invoking anonymous function, and then pass jQuery
to it.

Method 1: NoConflict

view plaincopy to clipboardprint?

var j = jQuery.noConflict(); 

// Now, instead of $, we use j. 

j(‘#someDiv’).hide(); 

Be careful with this method, and try not to use it when
distributing your code. It would really confuse the user of your script! 🙂

Method 2: Passing jQuery

view plaincopy to clipboardprint?

(function($) { 

    // Within this
function, $ will always refer to jQuery 

})(jQuery); 

The final parens at the bottom call the function automatically
– function(){}(). However, when we call the function, we also pass jQuery,
which is then represented by $.

Method 3: Passing $ via the Ready Method

view plaincopy to clipboardprint?

jQuery(document).ready(function($) { 

 // $ refers to
jQuery 

}); 

// $ is either undefined, or refers to some other
library’s function. 

6. Be Smart

 

// jQuery’s each method source 

    each: function(
object, callback, args ) { 

        var name, i
= 0, 

            length
= object.length, 

            isObj =
length === undefined || jQuery.isFunction(object); 

        if ( args )
{ 

            if (
isObj ) { 

                for
( name in object ) { 

                   
if ( callback.apply( object[ name ], args ) === false ) { 

                    
   break; 

                   
} 

               
} 

            } else
{ 

                for
( ; i < length; ) { 

                   
if ( callback.apply( object[ i++ ], args ) === false ) { 

                       
break; 

                   
} 

               
} 

            } 

        // A
special, fast, case for the most common use of each 

        } else
{ 

            if (
isObj ) { 

                for
( name in object ) { 

                   
if ( callback.call( object[ name ], name, object[ name ] ) === false )
{ 

                       
break; 

                   
} 

               
} 

            } else
{ 

                for
( var value = object[0]; 

                   
i < length && callback.call( value, i, value ) !== false;
value = object[++i] ) {} 

            } 

        } 

        return
object; 

    } 

Awful

view plaincopy to clipboardprint?

someDivs.each(function() { 

   
$(‘#anotherDiv’)[0].innerHTML += $(this).text(); 

}); 

Searches for anotherDiv for each iteration

Grabs the innerHTML property twice

Creates a new jQuery object, all to access the text of
the element.

Better

view plaincopy to clipboardprint?

var someDivs = $(‘#container’).find(‘.someDivs’), 

      contents =
[]; 

someDivs.each(function() { 

    contents.push(
this.innerHTML ); 

}); 

$(‘#anotherDiv’).html( contents.join(”) ); 

This way, within the each (for) method, the only task
we’re performing is adding a new key to an array…as opposed to querying the
DOM, grabbing the innerHTML property of the element twice, etc.

 

 

This tip is more JavaScript-based in general, rather than
jQuery specific. The point is to remember that jQuery doesn’t compensate for
poor coding.

Document Fragments

While we’re at it, another option for these sorts of
situations is to use document fragments.

view plaincopy to clipboardprint?

var someUls = $(‘#container’).find(‘.someUls’), 

    frag =
document.createDocumentFragment(), 

    li; 

someUls.each(function() { 

    li = document.createElement(‘li’); 

    li.appendChild(
document.createTextNode(this.innerHTML) ); 

   
frag.appendChild(li); 

}); 

$(‘#anotherUl’)[0].appendChild( frag ); 

The key here is that there are multiple ways to
accomplish simple tasks like this, and each have their own performance benefits
from browser to browser. The more you stick with jQuery and learn JavaScript,
you also might find that you refer to JavaScript’s native properties and
methods more often. And, if so, that’s fantastic!

jQuery provides an amazing level of abstraction that you
should take advantage of, but this doesn’t mean that you’re forced into using
its methods. For example, in the fragment example above, we use jQuery’s each
method. If you prefer to use a for or while statement instead, that’s okay too!

With all that said, keep in mind that the jQuery team
have heavily optimized this library. The debates about jQuery’s each() vs. the
native for statement are silly and trivial. If you are using jQuery in your
project, save time and use their helper methods. That’s what they’re there for!
🙂

10. jQuery and $

Ever wonder why/how you can use jQuery and $
interchangeably? To find your answer, view the jQuery source, and scroll to the
very bottom. There, you’ll see:

window.jQuery = window.$ = jQuery; 

The entire jQuery script is, of course, wrapped within a
self-executing function, which allows the script to limit the number of global
variables as much as possible. What this also means, though, is that the jQuery
object is not available outside of the wrapping anonymous function.

To fix this, jQuery is exposed to the global window
object, and, in the process, an alias – $ – is also created.

11. Conditionally Loading jQuery

HTML5 Boilerplate offers a nifty one-liner that will load
a local copy of jQuery if, for some odd reason, your chosen CDN is down.

view plaincopy to clipboardprint?

<!– Grab Google CDN jQuery. fall back to local if
necessary –> 

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script&gt; 

<script>!window.jQuery &&
document.write(‘<script
src="js/jquery-1.4.2.min.js"><\/script>’)</script> 

To "phrase" the code above: if window.jQuery is
undefined, there must have been a problem downloading the script from the CDN.
In that case, proceed to the right side of the && operator, and insert
a script linking to a local version of jQuery.

12. jQuery Filters

 

Premium Members: Download this Video ( Must be logged in)

Subscribe to our YouTube page to watch all of the video
tutorials!

view plaincopy to clipboardprint?

<script> 

   
$(‘p:first’).data(‘info’, ‘value’); // populates $’s data object to have
something to work with 

    $.extend( 

       
jQuery.expr[":"], { 

            block:
function(elem) { 

               
return $(elem).css("display") === "block"; 

            }, 

            hasData
: function(elem) { 

               
return !$.isEmptyObject( $(elem).data() ); 

            } 

        } 

    ); 

   
$("p:hasData").text("has data"); // grabs paras that
have data attached 

   
$("p:block").text("are block level"); // grabs only
paragraphs that have a display of "block" 

</script> 

Note: jQuery.expr[‘:’] is simply an alias for
jQuery.expr.filters.

13. A Single Hover Function

As of jQuery 1.4, we can now pass only a single function
to the hover method. Before, both the in and out methods were required.

Before

view plaincopy to clipboardprint?

$(‘#someElement’).hover(function() { 

  // mouseover 

}, function() { 

 // mouseout 

}); 

Now

view plaincopy to clipboardprint?

$(‘#someElement’).hover(function() { 

  // the toggle()
method can be used here, if applicable 

}); 

Note that this isn’t an old vs. new deal. Many times,
you’ll still need to pass two functions to hover, and that’s perfectly
acceptable. However, if you only need to toggle some element (or something like
that), passing a single anonymous function will save a handful of characters or
so!

14. Passing an Attribute Object

As of jQuery 1.4, we can now pass an object as the second
parameter of the jQuery function. This is helpful when we need to insert new
elements into the DOM. For example:

Before

view plaincopy to clipboardprint?

$(‘<a />’) 

  .attr({ 

    id :
‘someId’, 

    className :
‘someClass’, 

    href :
‘somePath.html’ 

  }); 

After

view plaincopy to clipboardprint?

$(‘</a>’, { 

    id :
‘someId’, 

    className :
‘someClass’, 

    href :
‘somePath.html’ 

}); 

Not only does this save a few characters, but it also makes
for cleaner code. In addition to element attributes, we can even pass jQuery
specific attributes and events, like click or text.

 

 

////////////////////

//////////////////////////////////////////////////////

http://refcardz.dzone.com/refcardz/jquery-selectors

http://www.mkyong.com/tutorials/jQuery-tutorials/

///////////////////////////

 

MATCHED SET METHODS

 

While the jQuery selectors give us great flexibility in
identifying which DOM elements are to be added to a matched set, sometimes
there are match criteria that cannot be expressed by selectors alone. Also,
given the power of jQuery method chaining, we may wish to adjust the contents
of the matched set between method invocations.

 

For these situations, jQuery provides methods that
operate not upon the elements within the matched set, but on the matched set
itself. This section will summarize those methods.

 

Adding New Elements

 

For adding new elements to a matched set, the add()
method is provided:

 

add(expression)

expression       (String)
A selector expression that specifies the DOM elements to be added to the
matched set, or an HTML string of new elements to create and add to the set.

(Element) A reference to an existing element to add.

(Array) Array of references to elements to add.

The add() method returns a new matched set that is the union
of elements in the original wrapped set and any elements either passed directly
as the expression argument, or matched by the selector of the expression
argument.

 

Consider:

 

$("div").add("p").css("color","red");

This statement creates a matched set of all <div>
elements, then creates a new matched set of the already matched <div>
elements and all <p> elements. The second matched set"s elements
(all <div> and all <p> elements) are then given the CSS color
property of "red".

 

You may think this is not all that useful because the
same could have been achieved with:

 

$("div,p").css("color","red");

But now consider:

 

$("div").css("font-weight","bold").add("p").
css("color","red");

Here the first created matched set of <div>
elements is assigned a bold rendition, and then the second matched set, with
<p> elements added, is colored red.

 

jQuery chaining (in which the css() method returns the
matched set) allows us to create efficient statements such as this one that can
accomplish a great deal with little in the way of script.

 

More Examples

 

$("div").add(someElement).css("border","3px
solid pink");

$("div")

.add([element1,element2])

.css("border","3px solid pink");

Removing Matched Elements

 

What if we want to remove elements from the matched set?
That"s the job of the not() method:

 

not(expression)

expression       (String)
A selector expression that specifies the DOM elements to be removed from the
matched set.

(Element) A reference to an existing element to remove.

(Array) Array of references to elements to remove.

Like add(), this method creates and returns a new matched
set, except with the elements specified by the expression argument removed. The
argument can be a jQuery selector, or references to elements to remove.

 

Examples

 

$("body
*").css("font-weight","bold")

.not("p").css("color","red");

Makes all body elements bold, then makes all but

 

elements red.

 

$("body
*").css("font-weight","bold")

.not(anElement).css("color","red");

Similar to the previous except the element referenced by
variable anElement is not included in the second set (and therefore not colored
red).

 

 

 

Avoid a typical beginner"s mistake and never confuse
the not() method, which will remove elements from the matched set, with the
remove() method, which will remove the elements in the matched set from the
HTML DOM!

 

Finding Descendants

 

Sometimes it"s useful to limit the search for
elements to descendants of already identified elements. The find() method does
just that:

 

find(expression)

expression       (String)
A selector expression that specifies which descendant elements are to be
matched.

Unlike the previously examined methods, find() only
accepts a selector expression as its argument. The elements within the existing
matched set will be searched for descendants that match the expression. Any
elements in the original matched set that match the selector are not included
in the new set.

 

Example

 

$("div").css("background-color","blue")

.find("img").css("border","1px
solid aqua");;

Selects all <div> elements, makes their background
blue, selects all <img> elements that are descendants of those
<div> elements (but not <img> elements that are not descendants)
and gives them an aqua border.

 

Filtering Matched Sets

 

When really fine-grained control is required for
filtering the elements of a matched set, the filter() method comes in handy:

 

filter(expression)

expression      

(String) A selector expression that specifies which
elements are to be retained.

 

(Function) A function used to determine if an element should
be included in the new set or not. This function is passed the zero-based
ordinal of the element within the original set, and the function context (this)
is set to the current element. Returning false as the function result causes
the element to not be included in the new set.

 

The filter() method can be passed either a selector
expression (comma-separated if more than one is desired) or a function. When
passed a selector, it acts like the inverse of not(), retaining elements that
match the selector (as opposed to excluding them). When passed a function, the
function is invoked for each element and decisions that cannot be expressed by
selectors can be made regarding the exclusion or inclusion of each element.

 

Examples

 

$(".bashful").show()

.filter("img[src$=.gif]").attr("title","Hi
there!");

Selects all elements with class name bashful, makes sure
that they are visible, filters the set down to just GIF images, and assigns a
title attribute to them.

 

$("img[src^=images/]").filter(function(){

return $(this).attr("title").match(/.+@.+\.com/)!=
null;

})

.hide();

Selects images from a specific folder, filters them to
only those whose title attribute matches a rudimentary .com email address, and
hides those elements.

 

Slicing and Dicing Matched Sets

 

Rather than matching elements by selector, we may
sometimes wish to slice up a matched set based upon the position of the
elements within the set. This section introduces two methods that do that for
us.

 

Both of these methods assume zero-based indexing.

 

slice(being,end)

begin   

(Number) The beginning position of the first element to
be included in the new set.

 

end      (Number)
The end position of the first element to not be included in the new set. If
omitted, all elements from begin to the end of the set are included.

Examples

 

$("body *").slice(2).hide();

Selects all body elements, then creates a new set
containing all but the first two elements, and hides them.

 

$("body *").slice(2,3).hide();

Selects all body elements, then creates a new set
containing the third element in the set and hides it. Note that the new set
contains just one element: that at position 2. The element at position 3 is not
included.

 

eq(position)

position           

(Number) The position of a single element to be included
in the new set.

 

The eq(n) method can be considered shorthand for
slice(n,n+1).

 

Matching by Relationship

 

Frequently we may want to create new matched sets based
upon relationships between elements. These methods are similar enough that
we"ll present them en masse in the following table:

 

Method            Description

children(expression)    Creates
a new matched set containing all unique children of the elements in the
original matched set that match the optional expression.

next(expression)          Creates
a new matched set containing unique following (next) siblings of the elements
in the original matched set that match the optional expression. Only
immediately following siblings are returned.

nextAll(expression)     Creates
a new matched set containing unique following (next) siblings of the elements
in the original matched set that match the optional expression. All following
siblings are returned.

parent(expression)       Creates
a new matched set containing unique immediate parents of the elements in the
original matched set that match the optional expression.

parents(expression)      Creates
a new matched set containing all ancestors of the elements in the original
matched set that match the optional expression.

prev(expression)          Creates
a new matched set containing unique preceding siblings of the elements in the
original matched set that match the optional expression. Only immediately
preceding siblings are returned.

prevAll(expression)     Creates
a new matched set containing unique preceding siblings of the elements in the original
matched set that match the optional expression. All preceding siblings are
returned.

siblings(expression)     Creates
a new matched set containing unique siblings of the elements in the original
matched set that match the optional expression.

contents()         Creates
a new matched set containing all unique children of the elements in the
original matched set including text nodes. When used on an <iframe>,
matches the content document.

For all methods that accept a filtering expression, the
expression may be omitted in which case no filtering occurs.

 

Translating Elements

 

There may be times that you want to translate the
elements within a matched set to other values. jQuery provides the map() method
for this purpose.

 

map(callback)

callback           (Function)
A callback function called for each element in the matched set. The return
values of the invocations are collected into an array that is returned as the
result of the map() method. The current element is set as the function context
(this) for each invocation.

For example, let"s say that you wanted to collect
the values of all form elements within a form named myForm:

 

var values = $("#myForm
:input").map(function(){

return $(this).val();

});

 

 

The map() function returns a jQuery object instance. To convert
this to a normal JavaScript array, you can use the get() method without
parameters:

 

var values = $("#myForm
:input").map(function(){

return $(this).val();

}).get();

In this case, values references a JavaScript array rather
than a jQuery wrapped object.

 

Controlling Chaining

 

All of the methods examined create new matched sets whose
contents are determined in the manner explained for each method. But what
happens to the original? Is it dismissed? It is not. When a new wrapped set is
created it is placed on the top of a stack of sets, with the top-most set being
the one to which any methods will be applied (as we have seen in the examples).
But jQuery allows you to "pop" the top-most set off that stack so
that you can apply methods to the original set. It does this with the end()
method:

 

end()

(no arguments)

Consider a previous example:

 

$("div").add("p").css("color","red");

As we recall, this creates a matched set of <div>
elements, then creates a new set that also contains the <p> elements.
Since this latter set is at the top of the stack when the css() method is
called, it is the second set that is affected. Now consider:

 

$("div").add("p").css("color","red").end().hide();

After the css() method is called, the end() method pops
the second set off the stack "exposing" the original set of just
<div> elements, which are then hidden.

 

Another useful method to affect how chaining the sets
operates is the andSelf() method:

 

andSelf()

(no arguments)

Calling andSelf() creates yet another new matched set that
is the union of the top two matched sets on the stack. This can be useful for
performing an action on a set, creating a new distinct set, and then applying a
method (or methods) to them all. Consider:

 

$("div").css("background-color","yellow")

.children("img").css("border","4px
ridge maroon")

.andSelf().css("margin","4em");

All <div> elements are selected and their
background set to yellow. Then, the <img> children of those <div>
elements are selected and have a border applied. Finally, the two sets are
merged, and a wide margin is applied to all <div> elements and their
<img> children.

 

Between jQuery selectors and the jQuery methods that
allow us to manipulate the matched sets, we can see that jQuery gives us some
powerful tools to select the DOM elements that we can then operate upon with
the many jQuery methods (as well as the dozens and dozens of jQuery plugins)
that are available to us.

///////////////Split

var arr =
$("#hfSelectedDays").val().split("#");

 for (var i = 0; i
< arr.length; i++) {

        
$("#" + arr[i]).addClass("active_day");

   }

//////////////////////////////

controlText = controlText.substring(0,
(controlText.indexOf("(") – 1)).trim();

$(".rate1").live("click", function ()
{

          });

 

//////////////////////////////

 if
($(‘[rel="’ + $(this).attr(‘name’) + ‘"]’).attr(‘checked’) ==
‘checked’) {

                   
$(‘[rel="’ + $(this).attr(‘name’) + ‘"]’).attr(‘checked’,
false);

 

//////////////////////////////

    <script
type="text/javascript">

//prm.add_beginRequest

        var prm =
Sys.WebForms.PageRequestManager.getInstance();

       
prm.add_endRequest(function (s, e) {

);

        });

    </script>

 

//////////////////////////////

//////////////////////////////

$(document).ready(function () {

            $(‘input[id$=tb1]’).bind(‘cut
copy paste’, function (e) {

               
e.preventDefault();

               
alert(‘You cannot ‘ + e.type + ‘ text!’);

            });

        });

 

//////////////////////////////

Handle copying pasing as well

<script type="text/javascript">

$(function() {

$(‘input.alpha[$id=tb1]’.bind(‘keyup blur’, function() {

if (this.value.match(/[^a-zA-Z0-9 ]/g)) {

this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, ”);

}

});

});

</script>

//////////////////////////////////ddl

<script type="text/javascript">

$(function() {

$(‘select[id$=DDL]’).bind("change keyup",
function() {

 

 

$(‘select[id$=DDL] :selected’).text());

 

});

});

</script>

keyup 4 IE

////////////////////////////////////ddl 2 Mddl

<script type="text/javascript">

$(function() {

var $conv = $(‘input[id$=btnConvert]’);

var $multi = $(‘input[id$=btnMulti]’);

$multi.hide();

 

$conv.click(function(e) {

e.preventDefault();

$(‘select[id$=DDL]’).attr("multiple",
"multiple");

$conv.hide();

$multi.show();

});

 

 

$multi.click(function(e) {

e.preventDefault();

$("#para").empty();

$(‘select[id$=DDL] :selected’).each(function(sel) {

$("#para").append($(this).text() + "<br
/>");

});

});

 

});

 

////////////////////////////////Sort ddl

<script type="text/javascript">

$(function() {

$(‘input[id$=btnSort]’).click(function(e) {

e.preventDefault();

var sortedDdl = $.makeArray($(‘select[id$=DDL] option’))

.sort(function(o, n) {

return $(o).text() < $(n).text() ? -1 : 1;

});

$("select[id$=DDL]").html(sortedDdl).val("1");

$("#para").html("Items were
Sorted!");

$(this).attr("disabled", "disabled");

});

});

</script>

////////////////////////////////TB Clone

<script type="text/javascript">

$(function() {

$(‘input[id$=tb1]’).keyup(function() {

var txtClone = $(this).val();

$(‘input[id$=tb2]’).val(txtClone);

});

});

</script>

/////////////////////////////////TB Focus

$("input:text:disabled").css("background-color","gray");

$("input:text:enabled:first").focus();

Live Demo

Similarly, if you want to set focus on the Textbox that is
both ‘Enabled’ and ‘has some value in it’, use

the code shown below, which in our case sets focus to the
fourth TextBox (tb4), since this is the only one

which qualifies being Enabled and being non-empty.

$("input:text[value!=]:enabled:first").focus();

/////////////////////////////////Read only Nonempt TB

$(function() {

$(‘input:text[value!=]’).each(function() {

$(this).attr(‘readonly’, true);

});

});

/////////////////////////////////

<script type="text/javascript">

$(function() {

$(‘input:text:first’).focus();

var $inp = $(‘input:text’);

$inp.bind(‘keydown’, function(e) {

var key = (e.keyCode ? e.keyCode : e.charCode);

if (key == 13) {

e.preventDefault();

var nxtIdx = $inp.index(this) + 1;

$(":input:text:eq(" + nxtIdx +
")").focus();

}

});

});

</script>

//////////////////////////////////////////Clone

<script type="text/javascript">

$(function() {

$(‘input[id$=tb1]’).keyup(function() {

var txtClone = $(this).val();

$(‘input[id$=tb2]’).val(txtClone);

});

});

</script>

 

Since we are capturing the keyup event, the contents are
cloned into the second textbox,

whenever the user pastes text in the first textbox using
Ctrl+v. This is however not true when the user right clicks the textbox and
chooses paste from the context menu.

 

//////////////////////////////////////////Click &
Select

$(function() {

$(‘input[id$=tb1]’).click(function() {

$(this).focus().select();

});

});

 

//////////////////////////////////////////Char # limit

<script type="text/javascript">

$(function() {

var limit = 50;

$(‘textarea[id$=tb1]’).keyup(function() {

var len = $(this).val().length;

Section 1 – jQuery and the ASP.NET TextBox

19 | P a g e

if (len > limit) {

this.value = this.value.substring(0, limit);

}

$(‘#charLeft’).text(limit – len + " characters left");

});

});

</script>

 

////

map

array

get

As Yehuda Katz says – “My mantra has always been:
keydown/keyup if you want to know the key that was pressed; keypress if you
want to know what text was detected”

If you want to accept only numbers, use /[^0-9 ]/g and
for accepting only alphabets, use /[^a-zA-Z

]/g. Also note that a user can right click the textbox
and choose paste from the context menu. In such

cases, the blur event detects the non-alphanumeric
characters as soon as the textbox looses focus.

 

keyCode represents the actual key pressed as a numerical
value, whereas charCode gives the

ASCII/Unicode value of the key press result (for eg:
Shift + A). Firefox and other browsers also support

e.which. IE and Opera do not support charCode.

 

 

//////////////////////////////////////////

//////////////////////////////////////////

//////////////////////////////////////////

 

 

            var
dataString = "{firstparam: ‘" + val1 + "’, secondparam: ‘"
+ val2 + "’}";

           
myRequest = jQuery.ajax({

                type: "POST",

               
url: "servicename.asmx/funcname",

               
data: dataString,

               
contentType: "application/json; charset=utf-8",

               
dataType: "json",

               
success: function (msg) {

                    //msg.d        }

            });

 

//////////////////////////////

return false from within a jQuery event handler is
effectively the same as calling both e.preventDefault and e.stopPropagation on
the passed jQuery.Event object.

e.preventDefault() will prevent the default event from
occuring, e.stopPropagation() will prevent the event from bubbling up and
return false will do both. Note that this behaviour differs from normal
(non-jQuer

//////////////////////////////

//////////////////////////////

    var a = new array()

    var b = new
array(8)

    var c = [1, 2,
"turtle", "number", true];

Javascript Array Properties and Functions

 

    b.length //

    c.concat(3,4)
//

    c.join(":
") // Returns a string with each element separated by a colon and a space.
1: 2: number: true

    c.slice(0, 2)
// Returns an array which contains all elements between the first value you
pass to the second value. In this example you would be returned [1, 2, number]

    c.sort()
//returns [1, 2, number, true, turtle]

    c.toString()

Javascript Date Functions

    a = new Date();
// Creates a new date object and assigns the current time to it

   
document.write(a.getTime()); : Returns a millisecond representation of a
date. ex. 1270487133410

    document.write(a.getDay());
: Returns the day of the week

   
document.write(a.getFullYear()); : Returns the year of the date

   
document.write(a.getHours()); : Returns the hours of the set date

   
document.write(a.getMinutes()); : Returns the minutes of the set date

    a.setTime(); :
Creates a millisecond representation of a date. ex. 1270487133410

   a.setDay(); :
Sets the day of the week

   a.setFullYear();
: Sets the year of the date

   a.setHours(); :
Sets the hours of the set date

   a.setMinutes();
: Sets the minutes of the set date

 

Javascript Math Functions

 

   
isNaN(variableToTest) : Returns true if the variable is a number and
false otherwise

   
Math.abs(variableToTest) : Performs an absolute value calculation

   
Math.ceil(variableToTest) : Rounds a number up

   
Math.floor(variableToTest) : Rounds a number down

    Math.max(x, y)
: Returns the larger of the two variables it is passed

    Math.min(x, y)
: Returns the smaller of the two variables it is passed

    Math.random():
Returns a random number

   
parseFloat(string) : Converts a string into a float number

   
parseInt(string) : Converts a string into an int number

 

Javascript String Functions

 

   
stringVariable.length : Returns the number of characters in a string

   
stringVariable.charAt(x) : Returns the character at the position sent to
this function

   
stringVariable.concat(x1, x2) : Adds one or more values to the end of
the string

   
stringVariable.indexOf(wordYourLookingFor, whereToStartSearch) :
Searches the string for a chosen word or character

   
stringVariable.match(regexp) : Look for a specific regular expression in
a string. See my Javascript Regular Expression tutorial if you don’t know what
they are.

    stringVariable.replace(regexp,
replacementText) : Search for a regular expression match and then replace the
match with the replacement text given

   
stringVariable.slice(startPoint, endPoint) : Extracts a string from the
beginning point to the ending point given

   
stringVariable.split(delimiter, maxLength) : Breaks a string into a
series of cells, by separating the words by the chosen delimiter. ex.
"1,2,3,4″.split(",") would return ["1","2","3","4"].
You have the option of defining a maximum number of elements in the array that
is created.

 

Javascript Document Functions

 

   
document.getElementsByName(idName) : Provides you with access to a node
on the web page by passing it the id Name.

   
document.write() : Appends text or variable values to the web page

   
document.writeln() : Appends text or variable values to the web page,
followed by a newline

 

/////////////

string()

toPrecision

toFixed

For example, the following returns "abc%26%25":

escape("abc&%")

//

The following example returns "ab!#":

unescape("ab%21%23")

///////////

arrayObject.length

The Array object has three methods:

    join: Joins all
elements of an array into a string.

    reverse:
Reverses elements of an array

    sort: Sorts
elements of an array based on a specified comparison function.

//////////////////////

String Object

identifierName = new String(stringValue)

stringValue can be a string literal or string-valued
variable.

7.7.2 Properties

A String object has one property, length.

x = mystring.length

7.7.3 Methods

indexOf

Returns the index within the calling string object of the
first occurrence of the specified value, starting the search at fromIndex.

stringName.indexOf(searchValue)

stringName.indexOf(searchValue, fromIndex)

searchValue is a string, representing the value to search
for.

fromIndex is the location within the calling string to
start the search from. It can be any integer from zero to stringName.length –
1.

Characters in a string are indexed from left to right.
The index of the first character is zero, and the index of the last character
is stringName.length – 1.

If searchValue is not found, JavaScript returns -1.

7.7.3.2 lastIndexOf

Returns the index within the calling string object of the
last occurrence of the specified value. The calling string is searched backward,
starting at fromIndex.

stringName.lastIndexOf(searchValue,)

stringName.lastIndexOf(searchValue, fromIndex)

It can be any integer from zero to stringName.length – 1.

Characters in a string are indexed from left to right.
The index of the first character is zero, and the index of the last character
is stringName.length – 1.

If you do not specify a value for fromIndex, lastIndexOf
assumes stringName.length – 1 (the end of the string) by default. If
searchValue is not found, lastIndexOf returns -1.

Example

var anyString="Brave new world"

//returns 8

anyString.indexOf("w")

//returns 10

anyString.lastIndexOf("w")

//returns 6

anyString.indexOf("new")

//returns 6

anyString.lastIndexOf("new"))

 

7.7.3.3 substring

 

stringName.substring(indexA, indexB)

indexA is any integer from zero to stringName.length –
1,.

indexB is any integer from zero to stringName.length –
1,.

Characters in a string are indexed from left to right.
The index of the first character is zero, and the index of the last character
is stringName.length – 1.

 

If indexA is less than indexB, the substring method
returns the subset starting with the character at indexA and ending with the
character before indexB. If indexA is greater than indexB, the substring method
returns the subset starting with the character at indexB and ending with the
character before indexA. If indexA is equal to indexB, the substring method
returns the empty string.

 

Example

 

The following example uses substring to display
characters from the string "Netscape":

 

var anyString="Netscape"

 

//returns "Net"

anyString.substring(0,3)

anyString.substring(3,0)

//returns "cap"

anyString.substring(4,7)

anyString.substring(7,4)

 

7.7.3.4 charAt

 

Returns the character at the specified index.

stringName.charAt(index)

index is any integer from zero to stringName.length – 1,.

Characters in a string are indexed from left to right.
The index of the first character is zero, and the index of the last character
is stringName.length – 1. If the index you supply is out of range, JavaScript
returns an empty string.

The following example displays characters at different
locations in the string "Brave new world":

var anyString="Brave new world"

// The character at index 0 is B

anyString.charAt(0))

// The character at index 3 is v

anyString.charAt(3)

7.7.3.5 toLowerCase

Returns the calling string value converted to lowercase.

stringName.toLowerCase()

Example

The following example returns the lowercase string
"alphabet":

var upperText="ALPHABET"

upperText.toLowerCase()

 

7.7.3.6 toUpperCase

var lowerText="alphabet"

lowerText.toUpperCase()

7.7.3.7 split

 

Splits a String object into an array of strings by
separating the string into substrings. Returns an Array object. Syntax:

 

stringName.split(separator)

 

stringName is a String object.

separator is string literal or expression that separates
the string into substrings. If separator is the empty string, split separates
each character into a substring element in the array.

//////////////////////////////////////////////////

 

 

string.substr(start, length);

start – the index of the character to begin extraction
at. This argument can actually be negative, in which case the characters are
counted not from the beginning but from the end of the string (see the examples
below). Note that using a negative value for start may not work in Internet
Explorer.

length – (optional) the length of the output string. If
left out, the whole remaining part of the string is extracted

var s = "abcdefghijklmn";

var a = s.substr(2, 3);

var d = s.substr(-3, 2);

// a == "cde"

// d == "lm"

string.indexOf(searchstring, start);

The method takes two arguments:

//////////////////////////////////

Method            Description

concat()           Combines
the text of two strings and returns a new string.

localeCompare()          Returns
a number indicating whether a reference string comes before or after or is the
same as the given string in sort order.

length()            Returns
the length of the string.

match()            Used
to match a regular expression against a string.

replace()          Used
to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.

search()            Executes
the search for a match between a regular expression and a specified string.

slice()   Extracts a
section of a string and returns a new string.

split()   Splits a
String object into an array of strings by separating the string into
substrings.

substr()            Returns
the characters in a string beginning at the specified location through the
specified number of characters.

substring()        Returns
the characters in a string between two indexes into the string.

toLocaleLowerCase()   The
characters within a string are converted to lower case while respecting the
current locale.

toLocaleUpperCase()   The
characters within a string are converted to upper case while respecting the
current locale.

toLowerCase() Returns
the calling string value converted to lower case.

toString()          Returns
a string representing the specified object.

toUpperCase() Returns
the calling string value converted to uppercase.

valueOf()         Returns
the primitive value of the specified objec

///////////////////////Void

<input type="button" value="Print"
onclick="window.print()" />

</script>

</head>

<body>

<p>Click the following link to see the result:
</p>

<a href="javascript:void(alert(‘Warning!!!’))">Click
me!</a>

</body>

</html>

///////////////////////////////////////////////////////

What are Cookies ?

 

Cookies are a plain text data record of 5 variable-length
fields:

    Expires : The
date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.

    Domain : The
domain name of your site.

    Path : The path
to the directory or web page that set the cookie. This may be blank if you want
to retrieve the cookie from any directory or page.

    Secure : If
this field contains the word "secure" then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction
exists.

    Name=Value :
Cookies are set and retrieved in the form of key and value pairs.

document.cookie = "key1=value1;key2=value2;expires=date";

Here expires attribute is option. If you provide this
attribute with a valid date or time then cookie will expire at the given date
or time and after that cookies’ value will not be accessible.

 

Note: Cookie values may not include semicolons, commas,
or whitespace. For this reason, you may want to use the JavaScript escape()
function to encode the value before storing it in the cookie. If you do this,
you will also have to use the corresponding unescape() function when you read
the cookie value.

Example:

 

   cookievalue=
escape(document.myform.customer.value) + ";";

  
document.cookie="name=" + cookievalue;

//–>

Reading Cookies:

The document.cookie string will keep a list of name=value
pairs separated by semicolons, where name is the name of a cookie and value is
its string value.

You can use strings’ split() function to break the string
into key and values as follows:

Example:

   var allcookies =
document.cookie;

   cookiearray  = allcookies.split(‘;’);

   for(var i=0;
i<cookiearray.length; i++){

      name =
cookiearray[i].split(‘=’)[0];

      value =
cookiearray[i].split(‘=’)[1];

     
alert("Key is : " + name + " and Value is : " +
value);

   }

}

 

Note: Here length is a method of Array class which
returns the length of an array. We will discuss Arrays in a separate chapter.
By that time please try to digest it.

This will produce following result. Now press the button
"Get Cookie" to see the cookies which you have set in previous section.

 

Note: There may be some other cookies already set on your
machine. So above code will show you all the cookies set at your machine.

Setting the Cookies Expiration Date:

You can extend the life of a cookie beyond the current
browser session by setting an expiration date and saving the expiration date
within the cookie. This can be done by setting the expires attribute to a date
and time.

Example:

The following example illustrates how to set cookie
expiration date after 1 Month :

   var now = new
Date();

   now.setMonth(
now.getMonth() + 1 );

   cookievalue =
escape(document.myform.customer.value) + ";"

  
document.cookie="name=" + cookievalue;

   document.cookie
= "expires=" + now.toUTCString() + ";"

Deleting a Cookie:

Sometimes you will want to delete a cookie so that
subsequent attempts to read the cookie return nothing. To do this, you just
need to set the expiration date to a time in the past.

Example:

 

The following example illustrates how to delete cookie by
setting expiration date one Month in past :

 

   var now = new
Date();

   now.setMonth(
now.getMonth() – 1 );

   cookievalue =
escape(document.myform.customer.value) + ";"

  
document.cookie="name=" + cookievalue;

   document.cookie
= "expires=" + now.toUTCString() + ";"

 

Note: Instead of setting date, you can see new time using
setTime() function

/////////////////////////////////////////////////

 

 

A regular expression is an object that describes a
pattern of characters.

Syntax:

A regular expression could be defined with the RegExp( )
constructor like this:

var pattern = new RegExp(pattern, attributes);

or simply

var pattern = /pattern/attributes;

    pattern: A
string that specifies the pattern of the regular expression or another regular
expression.

    attributes: An
optional string containing any of the "g", "i", and
"m" attributes that specify global, case-insensitive, and multiline
matches, respectively.

 

Brackets:

Brackets ([]) have a special meaning when used in the
context of regular expressions. They are used to find a range of characters.

Expression       Description

[…]       Any one
character between the brackets.

[^…]     Any one
character not between the brackets.

[0-9]    It matches
any decimal digit from 0 through 9.

[a-z]     It matches
any character from lowercase a through lowercase z.

[A-Z]   It matches
any character from uppercase A through uppercase Z.

[a-Z]    It matches
any character from lowercase a through uppercase Z.

 

The ranges shown above are general; you could also use the
range [0-3] to match any decimal digit ranging from 0 through 3, or the range
[b-v] to match any lowercase character ranging from b through v.

Quantifiers:

 

The frequency or position of bracketed character
sequences and single characters can be denoted by a special character. Each
pecial character having a specific connotation. The +, *, ?, and $ flags all
follow a character sequence.

Expression       Description

p+        It matches
any string containing at least one p.

p*        It matches
any string containing zero or more p’s.

p?        It matches
any string containing one or more p’s.

p{N}    It matches
any string containing a sequence of N p’s

p{2,3} It matches
any string containing a sequence of two or three p’s.

p{2, }   It matches
any string containing a sequence of at least two p’s.

p$        It matches
any string with p at the end of it.

^p        It matches
any string with p at the beginning of it.

Examples:

Following examples will clear your concepts about
matching chracters.

Expression       Description

[^a-zA-Z]         It
matches any string not containing any of the characters ranging from a through
z and A through Z.

p.p       It matches
any string containing p, followed by any character, in turn followed by another
p.

^.{2}$ It matches
any string containing exactly two characters.

<b>(.*)</b>      It
matches any string enclosed within <b> and </b>.

p(hp)* It matches
any string containing a p followed by zero or more instances of the sequence
hp.

Literal characters:

Character         Description

Alphanumeric  Itself

         The NUL
character (\u0000)

\t          Tab (\u0009)

\n         Newline
(\u000A)

\v         Vertical
tab (\u000B)

\f          Form
feed (\u000C)

\r          Carriage
return (\u000D)

\xnn     The Latin
character specified by the hexadecimal number nn; for example, \x0A is the same
as \n

\uxxxx The Unicode
character specified by the hexadecimal number xxxx; for example, \u0009 is the
same as \t

\cX       The
control character ^X; for example, \cJ is equivalent to the newline character
\n

Metacharacters

A metacharacter is simply an alphabetical character
preceded by a backslash that acts to give the combination a special meaning.

For instance, you can search for large money sums using
the ‘\d’ metacharacter: /([\d]+)000/, Here \d will search for any string of
numerical character.

Following is the list of metacharacters which can be used
in PERL Style Regular Expressions.

 

Character                     Description

.              a
single character

\s             a
whitespace character (space, tab, newline)

\S            
non-whitespace character

\d             a
digit (0-9)

\D             a
non-digit

\w             a
word character (a-z, A-Z, 0-9, _)

\W             a
non-word character

[\b]           a
literal backspace (special case).

[aeiou]       
matches a single character in the given set

[^aeiou]      
matches a single character outside the given set

(foo|bar|baz) 
matches any of the alternatives specified

 

Modifiers

 

Several modifiers are available that can make your work
with regexps much easier, like case sensitivity, searching in multiple lines
etc.

Modifier          Description

i           Perform
case-insensitive matching.

m         Specifies
that if the string has newline or carriage return characters, the ^ and $
operators will now match against a newline boundary, instead of a string
boundary

g          Perform a
global matchthat is, find all matches rather than stopping after the first
match.

RegExp Properties:

 

Here is a list of each property and their description.

Property           Description

constructor       Specifies
the function that creates an object’s prototype.

global   Specifies
if the "g" modifier is set.

ignoreCase       Specifies
if the "i" modifier is set.

lastIndex          The
index at which to start the next match.

multiline          Specifies
if the "m" modifier is set.

source  The text of
the pattern.

RegExp Methods:

 

Here is a list of each method and its description.

Method            Description

exec()  Executes a
search for a match in its string parameter.

test()    Tests for
a match in its string parameter.

toSource()        Returns
an object literal representing the specified object; you can use this value to
create a new object.

toString()          Returns
a string representing the specified object

/////////////////////////////////////////////////

/////////////////////////////////////////////////

There are three types of errors in programming: (a)
Syntax Errors and (b) Runtime Errors (c) Logical Errors:

Syntax errors:

Syntax errors, also called parsing errors, occur at
compile time for traditional programming languages and at interpret time for
JavaScript.

 

Runtime errors:

For example, the following line causes a run time error
because here syntax is correct but at run time it is trying to call a non
existed method:

<script type="text/javascript">

<!–

window.printme();

//–>

</script>

Logical errors:

The try…catch…finally Statement:

The latest versions of JavaScript added exception
handling capabilities. JavaScript implements the try…catch…finally
construct as well as the throw operator to handle exceptions.

<script type="text/javascript">

<!–

try {

    // Code to run

    [break;]

} catch ( e ) {

    [break;]

}[ finally {

}]

//–>

</script>

 

 When an exception occurs
in the try block, the exception is placed in e and the catch block is executed.

Examples:

 

Here is one example where we are trying to call a non
existing function this is causing an exception raise. Let us see how it behaves
without with try…catch:

 

<!–

function myFunc()

{

   var a = 100;

 

  
alert("Value of variable a is : " + a );

 

}

//–>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click
Me" onclick="myFunc();" />

</form>

</body>

</html>

 

To understand it in better way you can Try it yourself.

 

Now let us try to catch this exception using try…catch
and display a user friendly message. You can also suppress this message, if you
want to hide this error from a user.

 

<html>

<head>

<script type="text/javascript">

<!–

function myFunc()

{

   var a = 100;

  

   try {

     
alert("Value of variable a is : " + a );

   } catch ( e ) {

     
alert("Error: " + e.description );

   }

}

//–>

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click
Me" onclick="myFunc();" />

</form>

</body>

</html>

 

To understand it in better way you can Try it yourself.

 

You can use finally block which will always execute
unconditionally after try/catch. Here is an example:

 

function myFunc()

{

   var a = 100;

  

   try {

     
alert("Value of variable a is : " + a );

   }catch ( e ) {

     
alert("Error: " + e.description );

   }finally {

     
alert("Finally block will always execute!" );

   }

}

//–>

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click
Me" onclick="myFunc();" />

</form>

</body>

</html>

 

To understand it in better way you can Try it yourself.

The throw Statement:

 

You can use throw statement to raise your built-in
exceptions or your customized exceptions. Later these exceptions can be
captured and you can take an appropriate action.

 

Following is the example showing usage of throw
statement.

 

<html>

<head>

<script type="text/javascript">

<!–

function myFunc()

{

   var a = 100;

   var b = 0;

  

   try{

      if ( b == 0
){

         throw(
"Divide by zero error." );

      }else{

         var c = a
/ b;

      }

   }catch ( e ) {

     
alert("Error: " + e );

   }

}

//–>

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click
Me" onclick="myFunc();" />

</form>

</body>

</html>

 

To understand it in better way you can Try it yourself.

 

You can raise an exception in one function using a string,
integer, Boolean or an object and then you can capture that exception either in
the same function as we did above, or in other function using try…catch
block.

The onerror() Method

 

The onerror event handler was the first feature to
facilitate error handling for JavaScript. The error event is fired on the
window object whenever an exception occurs on the page. Example:

 

<html>

<head>

<script type="text/javascript">

<!–

window.onerror = function () {

   alert("An
error occurred.");

}

//–>

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click
Me" onclick="myFunc();" />

</form>

</body>

</html>

 

To understand it in better way you can Try it yourself.

 

The onerror event handler provides three pieces of
information to identify the exact nature of the error:

 

    Error message .
The same message that the browser would display for the given error

 

    URL . The file
in which the error occurred

 

    Line number .
The line number in the given URL that caused the error

 

Here is the example to show how to extract this
information

 

<html>

<head>

<script type="text/javascript">

<!–

window.onerror = function (msg, url, line) {

  
alert("Message : " + msg );

   alert("url
: " + url );

   alert("Line
number : " + line );

}

//–>

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click
Me" onclick="myFunc();" />

</form>

</body>

</html>

 

You can display extracted information in whatever way you
think it is better.

 

To understand it in better way you can Try it yourself.

 

You can use onerror method to show an error message in
case there is any problem in loading an image as follows:

 

<img src="myimage.gif"

   
onerror="alert(‘An error occurred loading the image.’)" />

 

You can use onerror with many HTML tags to display
appropriate messages in case of errors

//////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////

function Redirect()

{   
window.location="http://www.newlocation.com&quot;;}

document.write("You will be redirected to main page
in 10 sec.");

setTimeout(‘Redirect()’, 10000);

 

//////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////

var int=self.setInterval(function(){clock()},1000);

function clock()

  {

  var d=new Date();

  var
t=d.toLocaleTimeString();

 
document.getElementById("clock").value=t;

  }

////

var
t=setTimeout(function(){alert("Hello")},3000)

 

/////////////////////////////////////////////////

<input type="button" value="Print"
onclick="window.print()" />

/////////////////////////////////////////////////

Creating a Navigation Frame

<frameset COLS="*,*">

<frame NAME="left"
SRC="left.html">

<frame NAME="right"
SRC="about:blank">

</frameset>

<aa HREF="#"

onClick="parent.right.location=’order.html’;

        
window.location=’ordernav.html’">

Order form</aa>

<aa HREF="#"

onClick="parent.right.location=’email.html’;

        
window.location=’emailnav.html’">

Email</aa>

<aa HREF="#"

onClick="parent.right.location=’sales.html’;

        
window.location=’salesnav.html’">

Sales Dept.</a>

 

If you’re only loading one document when the user clicks
on a link, you can use the TARGET attribute of the <a> tag and avoid
JavaScript. However, using JavaScript allows you to update two frames at once,
as seen in this example.

 

//////////////////////////////////////////////////

http://jsfiddle.net/jonathon/XTY5c/

https://www.informit.com/library/content.aspx?b=STY_JavaScript_24_hours&seqNum=124

///////////////////////////////////

Browsers
do Not Support JavaScript

Browsers that do not support JavaScript, will display
JavaScript as page content.

To prevent them from doing this, and as a part of the
JavaScript standard, the HTML comment tag should be used to "hide"
the JavaScript.

Just add an HTML comment tag <!– before the first
JavaScript statement, and a –> (end of comment) after the last JavaScript
statement, like this:

<!–
document.getElementById("demo").innerHTML=Date();
//–>

The two forward slashes at the end of comment line (//) is the
JavaScript comment symbol. This prevents JavaScript from executing the –>
tag.

 

////////////

The semicolon is optional (according to the JavaScript
standard), and the browser is supposed
to interpret the end of the line as
the end of the statement. Because of this you will often see examples without
the semicolon at the end.Note: Using semicolons makes it possible to write
multiple statements on one line.

////////////////////////////////////////////////////////////////

 

·        
Variable names must begin with a letter or
the underscore character

Note: Because JavaScript is case-sensitive, variable names
are case-sensitive.

 

Global
JavaScript Variables

Variables declared outside a function become GLOBAL,
and all scripts and functions on the web page can access it.

Global variables are destroyed when you close the page.

If you declare a variable, without using "var", the
variable always becomes GLOBAL.

Note: When you assign a text value to a variable, use
quotes around the value.

Note: If you redeclare a JavaScript variable, it will not
lose its value.

 

 

 

////////////////////////////////////////////////////////////////

Adding
Strings and Numbers

The rule is: If you add a number and a string, the result
will be a string!

Comparison
Operators

Comparison operators are used in logical statements to
determine equality or difference between variables or values.

Given that x=5, the table below explains the comparison
operators:

Operator

Description

Example

==

is equal to

x==8 is false
x==5 is true

===

is exactly equal to (value and type)

x===5 is true
x==="5" is false

 

Conditional
Operator

JavaScript also contains a conditional operator that assigns a
value to a variable based on some condition.

Example

greeting=(visitor=="PRES")?"Dear
President ":"Dear ";

////////////////////////////////////////////////////////////////

 

var d=new Date();
var theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I’m looking forward to this weekend!");
}
</script>

////////////////////////////////////////////////////////////////

Insert
Special Characters

The backslash (\) is used to insert apostrophes, new lines,
quotes, and other special characters into a text string.

\’ single quote \" double quote \\ backslash \n new line
\r carriage return \t tab \b backspace \f form feed

In JavaScript, a string is started
and stopped with either single or double quotes

 

////////////////////////////////////////////////////////////////

 

 

JavaScript
Timing Events

·        
setTimeout() – executes a code some time in the
future

·        
clearTimeout() – cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both
methods of the HTML DOM Window object.

 

The
setTimeout() Method

Syntax

var t=setTimeout("javascript
statement
",milliseconds);

The
clearTimeout() Method

 

document.getElementById("frm1").reset();

document.getElementById("frm1").submit();

document.write(document.title);

alert(event.keyCode);

 

//////////////////////////////////////////////////////////////////////////////////////////////////////

 

 

Writing JavaScript in HTML and Calling it from Code
behind.

        function
myFunction(str)

        {

           
alert(str);

        }

   

1) Without Using RegisterStartupScript In Code behind

 

protected void Page_Load(object sender, EventArgs e)

 {

  
Button2.Attributes.Add

  
("onclick", "javascript:myFunction(‘from code
behind’);");

 }

 

image

 

 

2) Using RegisterStartupScript in Code Behind

 

protected void Button3_Click(object sender, EventArgs e)

{

 Page.ClientScript.RegisterStartupScript

 (typeof(testJavaScript), "alert",

 "myFunction(‘" + TextBox1.Text +
"’);");

}

 

 

*Using RegisterStartupScript we can call javascript from
code behind.

 

       

       

    </div>

   

 

///////////////////////////

]]]]]]]]]]]]]]]]]]]]]]]]

                string script =
"<script language=javascript>window.alert(‘The Services information
has been updated successfully.’);</script>";

                if
(!IsStartupScriptRegistered("clientScript"))

                   
Page.RegisterStartupScript("clientScript", script);

 

 

//////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////

    
var
emailPat =
/^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
     var
emailid=document.getElementById("<%=txtEmail.ClientID
%>"
).value;
     var
matchArray = emailid.match(emailPat);
     if
(matchArray == null)
    {
               alert("Your email address seems incorrect. Please try
again."
);
               document.getElementById("<%=txtEmail.ClientID %>").focus();
              
return
false;
    }
//////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
D

 

 

<script type="text/javascript">

            $("document").ready(function(){

                        $("div.contents").css("min-height",document.height-270+"px")

            })

</script>

 

        function
SelectGroup(src, args) {

            if
(document.getElementById("ctl00_ContentPlaceHolder1_ddlCategories").selectedIndex
== "0") {

                args.IsValid = false;

            }

            else
{

                args.IsValid = true;

            }

        }

 

 

//////////

a. When you use RegisterStartupScript, it will render your script after all the elements in the
page (right before the form’s end tag). This enables the script to call or
reference page elements without the possibility of it not finding them in the
Page’s DOM.

Here is the rendered source
of the page when you invoke the
RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml&quot;
<head id=
"Head1"><title></title></head> 
<body>    <form name="form1"
method=
"post" action="StartupScript.aspx"
id=
"form1"<div> 
<input type=
"hidden"
name=
"__VIEWSTATE" id="__VIEWSTATE"
value=
"someViewstategibberish" /> 
</div> 
<div> 
  <span id=
"lblDisplayDate">Label</span><br
/>    <input type=
"submit"
name=
"btnPostback" value="Register
Startup Script"
id="btnPostback"
/>    <br />    <input type=
"submit"
name=
"btnPostBack2" value="Register"
id=
"btnPostBack2" /> 
</div> 
<div> 
  <input type=
"hidden"
name=
"__EVENTVALIDATION" id="__EVENTVALIDATION"
value=
"someViewstategibberish" /> 
</div>  <!–
Note
this part –>  <script
language=
‘javascript’
var lbl = document.getElementById(‘lblDisplayDate’); 
lbl.style.color=
‘red’
</script> 
</form>  <!– Note
this part –>  </body> 
</html> 

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before
any of the page elements. Since this is a direct script (not a function that
can be called, it will immediately be executed by the browser. But the
browser does not find the label in the Page’s DOM at this stage and hence you
should receive an "Object not found" error.

Here is the rendered source
of the page when you invoke the
RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml&quot;
<head id=
"Head1"><title></title></head> 
<body>    <form name="form1"
method=
"post" action="StartupScript.aspx"
id=
"form1">    <div> 
  <input type=
"hidden"
name=
"__VIEWSTATE" id="__VIEWSTATE"
value=
"someViewstategibberish" /> 
  </div>  <script language=
‘javascript’
var lbl = document.getElementById(‘lblDisplayDate’); 
// Error is thrown in the next line because lbl is null. 
lbl.style.color=
‘green’

Therefore, to summarize, you
should call the latter method if you intend to render a function definition.
You can then render the call to that function using the former method (or
add a client side attribute).

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

RegisterClientScriptBlock is
for returning blocks of client-side script containing functions.
RegisterStartupScript is for returning blocks of client-script not  
packaged in functions-in other words, code that’s to execute when the page is
loaded. The latter positions script blocks near the end of the document so
elements on the page that the script interacts are loaded before the script
runs.

,,,,,,,,,,,,,………….,,,,,,,,,,,,,,,

Code
Snip-it 1:
RegisterClientScript(

    "CS1",
    "<script language=/"javascript/">"
+
        "window.alert(
document.form[0].txtElement.value );" +
        "</script>" );

Code Snip-it 2:
RegisterClientScript(

    "CS2",
    "<script language=/"javascript/">"
+
        "function a(){window.alert(
document.form[0].txtElement.value );}" +
        "</script>" );

Code Snip-it 3:
RegisterStartupScript(

    "CS3",
    "<script language=/"javascript/">"
+
        "window.alert(
document.form[0].txtElement.value );" +
        "</script>" );

Code Snip-it 4:
RegisterStartupScript(

    "CS4",
    "<script language=/"javascript/">"
+
        "function b(){window.alert(
document.form[0].txtElement.value );}" +
        "</script>" );

OK so there are some example scripts. Now CS1 and CS3 will be executed as soon
as the web page parses them. The problem is CS1 is parsed and run before
any form element have been created by the web browser, whereas CS3 is parsed
and run after the form elements are created. So CS1 will execute and throw an
error telling you that there is craziness in the world as there is no object in
the form called txtElement, so you definitely cannot find out what its value
is.  CS3 on the otherhand will work fine as txtElement will have been
created in the form object.

CS2 and CS3 are effectively the same thing with the assumption that they are
called by some user action.

So I recommend RegisterClientScript for any functions that will be called by
user actions such as mouseovers etc.
I recomment RegisterStartupScript for any initialisation that needs to be done,
such as setting the time in a textbox based on the web browsers time. If you
are going to create a function that is called by the window.onload event then
RegisterClientStartup and RegisterStartupScript will have the same effect, just
place the script in a different part of your output HTML.

 

string
scriptCode = "<script language=javascript> window.alert(‘Account has
been modified successfully.’); window.opener.location.reload();
window.close();  </script>";

           
if (
!IsStartupScriptRegistered("clientScript"))

               
Page.RegisterStartupScript("clientScript",
scriptCode);

 

///////////////////////////////

 

function
resetOtherDLLs(fld ,name) {

       
//window.alert("Done");

       
frm = fld.form;

       
thisName = fld.Name;

       
a = 0;

 

       
//window.alert(name);

       
for (i = 0; i < frm.length; i++) {

 

           

           
if (frm.elements[i].type == "select-one") {

 

               

               
if (frm.elements[i].name != name) {

 

               
//    window.alert(frm.elements[i].name + "  = 
" + thisName)

               
//if (a != 0) {

                   
frm.elements[i].selectedIndex = 0;

                   
//window.alert(frm.elements[i].name + "  =  " + thisName)

               
}

//               
else {

//                   
window.alert(frm.elements[i].name + "  =  " + name)

//               

//               
}

                   
a = 1;

              
// }

           
}

       
}

       

   
}

 

 

</script>

 

 

//////////////////////////////

 

   
<asp:DropDownList onChange="javascript:resetOtherDLLs(this,
‘ctl00$ContentPlaceHolder1$ddlPeriod’  );">

 

/////////////////////////////////////////

  <asp:CheckBox onclick="ShowPrompt();" ID="chkDefault" runat="server" Text="Also save as
Default Value?"
/>

 

<script language="javascript" type="text/javascript">

        function ShowPrompt() {

           
var chk =
document.getElementById(
"<%=chkDefault.ClientID%>");

           
if (chk.checked)

               
alert(
"By
selecting this option, the Default Contents will be updated and previous save
can not be retrieved again."
);

        }

    </script>

 

///////////////////////////////////////////////////////////

 

 

Close
Window

A close window function is useful when you use a pop-up
window on your page, as it allows the visitor to easily close the window. You
can do it several ways: To use a button, paste the following where you want the
button to appear:

<form>

<input type=button
value="Close Window"
onClick="javascript:window.close();">

</form>

For a text link, paste the following where you want the link
to appear:

<a
href="javascript:window.close();">Click to Close Window</a>

To make the window close after a given number of seconds, add
the event handler to the <body> tag. FYI, 20000 equals 20 seconds.

<BODY
onLoad="setTimeout(window.close,20000)">

 

 

JavaScript
Back Button

Just like your browser’s back button, the following script
allows the user to press a button to returns the user to the previous page.
Paste the following code where you want the button to appear on your page:

<FORM>

<INPUT
TYPE="Button" VALUE="Previous Page" onClick="history.go(-1)">

</FORM>

If you would rather use a link, paste the following code
where you want the link to appear:

<a href="javascript:history.back(1)">Previous
Page</a>

 

 

Focus
OnLoad

You can put the user’s cursor inside a text box (calling the
text box’ focus) as soon as the page is loaded. This helps ensure that visitors
do not ‘overlook’ an important form item on your site. It only uses one line of
code! This part goes into your body tag:

 

<BODY
OnLoad="document.nameform.user.focus();">

 

Then you just use the name of the form and field name within
your form (you can change the form and field names, but need to do so within
the function and the form):

 

<form name="nameform">

Name:  <input type=text name=user
size=10>

</form>

 

7.  <tr onMouseOver="this.style.background=’#000000′; this.style.color=’#FFFFFF’" onMouseOut="this.style.background=’#FFFFFF’; this.style.color=’#000000’">   

 

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Creating Popup Windows

There maybe
times that you do not want a user to navigate away from your site, because you
want to show them something, but still have more data that you would like to
give them. A good example of this is if you want to show them a picture for a
news story. Using JavaScript you can make the link open in a new window. We
will be using the window.open() function that is built into JavaScript. The
window.open function has a special formating that we need to look at before we
use it.
window.open(URL, Title, attributes)
To use the window.open function we have to tell it the source of our image, or
web site, the title of the new window, and then if we want to customize the
window we can pass it other attributes that the function will understand, like
toolbar=no. Here is a list of attributes that you can pass to the window.open
function.

Attribue

Action

Width

This attribute will set the width of the new
window.

Height

Based on the name of this attribute, you could
have guessed correctly that this sets the height of the window.

Resizable

Like the rest of the attributes in this list,
you can set this to either yes or no. It allows the window to resized by the
user.

Scrollbars

The scrollbars attribute will show or hide the
scrollbars on the window.

Toolbar

Like the scrollbars, this will either hide or
show the toolbar of the browser. The toolbar is location where the back,
foward, reload, stop buttons are located.

Location

Location will allow you to show or not show the
url box, this is the box you type in the address of the site you want to go
to, like http://www.code-sucks.com

Directories

If directories is set to no, then it will not
show toolbars that the user has, like a Favorites toolbar.

Status

The status bar hides the bar at the very bottom
of the browser that shows how much of the page that is loaded.

Menubar

The menubar is the part of the browser that has
File, Edit, View, etc. Set this so no to hide this bar.

Copyhistory

This allows you to copy the history of the
parent window to the new window.


With the new information, lets create a function that will allow us to open web
sites, and images in new windows.

view
plainHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
?

1.   <script lanuage="JavaScript" type="text/Javascript">   

2.    function popup(lightbulb){
  

3.       popupWindow= window.open(lightbulb, "Pop Up""toolbar=no")   

4.       popupWindow.focus()
  

5.    }   

6.   </script>  

<script lanuage="JavaScript"
type="text/Javascript">

 function
popup(lightbulb){

popupWindow=
window.open(lightbulb, "Pop Up", "toolbar=no")

popupWindow.focus()

 }

</script>

Since we may
use this code again, we created a function. This will make our code appear
neater, and run faster since we do not have to rewrite all of the code, and the
browser does not have to process it. What this function does is passes a
varible to the window.open function. Then using the focus() method, we open the
new window when the link is clicked. Now when we want to open a new window, we
will just pass a varible to the function.

view
plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
?

1.   <a href="javascript:popup(‘lightbulb_on.jpg’)">Lights On</a>  

 

 

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Changing Images based on Time

If you ever
used Google’s iGoogle feature, you may have noticed that depending on the hour,
the background changes. Using JavaScript we can create the same feature, which
will rotate an image based on the time that the the user visits.
Here are the three images that we are going to be using.

view plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=changing_images_based_on_time.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=changing_images_based_on_time.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=changing_images_based_on_time.php"
?

1. <script language="JavaScript" type="text/javascript">   

2.  var now = new Date();
  

3.  var hour = now.getHours();
  

4.   

5.  if (hour <=11){
  

6.     var TimeofDay = "<IMG src="images/morning.jpg">"  

7.  }else if(hour > 11 && hour <= 17){
  

8.     var TimeofDay = "<IMG src="images/afternoon.jpg">"  

9.  }else if(hour > 17){
  

10.     var TimeofDay = "<IMG src="images/night.jpg">"  

11.  }
  

12. </script>
  

13.   

14. <script>
  

15.     document.write(TimeofDay)
  

16. </script>  

<script language="JavaScript"
type="text/javascript">

 var now = new
Date();

 var hour =
now.getHours();

 

 if (hour
<=11){

            var
TimeofDay = "

"

 }else if(hour
> 11 && hour <= 17){

            var
TimeofDay = "

"

 }else if(hour
> 17){

            var
TimeofDay = "

"

 }

</script>

 

<script>

document.write(TimeofDay)

</script>

The first thing
we need to do in our script is to find what hour it currently is. We used the
Date() function to do this. This is nothing that we have not seen already in
earlier tutorials. We are then going to use two functions to determine what
image to display. In our script we will have any time before 11 to display a
sunrise, any time between 12 to 17 to display the afternoon image, and any time
greater then 17 to show our night sky image. Later in the body, when we want to
display the image we use the document.write, and pass the TimeofDay to it.
Below is an example of the code in action.

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Specify
Referring Page

This script makes sure that your visitor can only reach a
given page from the page that you specify. Paste the following before the
ending head tag on the page:

<SCRIPT
LANGUAGE="JavaScript">

var allowedreferrer = "http://www.yoursite.com/referringpagename.htm";

if
(document.referrer.indexOf(allowedreferrer) == -1) {

alert("You can only
access this page from " + allowedreferrer);

window.location=allowedreferrer;

}

</script>

That’s it! If you know of some other script snippets, let us
know using the comments below and we will add them to this article!

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Window
Close Automatically

 

<!–  Place this snippet in the body tag of the
popup window.

onLoad="setTimeout(‘window.close()’, 5000);"

 

 

Window
Close Method

 

<!– Paste this code into the BODY section of your HTML
document  –>

 

<button type="button"
onclick="window.close()">Close Window</button>

<p><div align="center">

<font face="arial, helvetica"
size"-2">Free JavaScripts provided<br>

by <a href="http://javascriptsource.com">The
JavaScript Source</a></font>

</div><p>

 

 

<script type="text/javascript">

<!–

var i;

i=1;

for(i=1;i<2;i++) {

  
window.open("www.javascriptsource.com")

}

//–>

</script>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Redirect with a Timer

There maybe
times that you want to redirect a visitor on your site. In JavaScript, you can
use window.location to redirect a user to a different page. You may have seen
this used by sites with full page ads, or to redirect users to the site’s new
domain name. You can add a timer to the script that will allow the page to redirect
and the user will not need to click a link or type in the new URL.

view plainHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=redirect_with_timer.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=redirect_with_timer.php"
printHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=redirect_with_timer.php"
?

1. <script language="JavaScript" type="text/javascript">   

2. var count =6   

3. var redirect="http://www.code-sucks.com&quot;  

4.   

5. function countDown(){   

6.  if (count <=0){   

7.   window.location = redirect;
  

8.  }else{   

9.   count–;
  

10.   document.getElementById("timer").innerHTML = "This page will redirect in "+count+" seconds."  

11.   setTimeout("countDown()", 1000)
  

12.  }
  

13. }
  

14. </script>
  

15.   

16. Our webpage has moved.  Please update your bookmarks for the new site.
  

17.   

18. <span id="timer">   

19. <script>
  

20.  countDown();
  

21. </script>
  

22. </span>  

<script language="JavaScript"
type="text/javascript">

var count =6

var redirect="http://www.code-sucks.com&quot;

 

function countDown(){

 if (count
<=0){

 
window.location = redirect;

 }else{

  count–;

 
document.getElementById("timer").innerHTML = "This page
will redirect in "+count+" seconds."

 
setTimeout("countDown()", 1000)

 }

}

</script>

 

Our webpage has moved.  Please update your bookmarks for the new
site.

 

<span id="timer">

<script>

 countDown();

</script>

</span>

So the
script is redirecting the user since the site’s domain name has been changed. The
first thing the script does is set two variables, one is named count, and the
other is named redirect. We see that redirect is set to the URL that we want
the user to be redirected to, and count that is set to six. We then see a
function called countDown. Inside this function we see an if else statement. It
tells us that if count is less than or equal to zero, then we want the window
location to be the value or our redirect variable. The else part of the
function subtracts one from count, then displays the value of count, along with
the sting This page will redirect in seconds. The last part of the else sets a
timer with the setTimeout function built into JavaScript. We tell the
setTimeout function to run the countDown function every 1000 milisecond, or every
second. Below is an example of the code, but without the redirect. If you
loaded the page over five seconds ago, then just reload the page to see the
example.

The page would have redirected at this point.

///////////////////////////

 

string scriptCode =
"<script language=javascript> window.alert(‘Account has been
modified successfully.’); window.opener.location.reload();
window.close();  </script>";

           
if (!IsStartupScriptRegistered("clientScript"))

               
Page.RegisterStartupScript("clientScript",
scriptCode);

/////////////////////////////////////////////////////////////

a. When you use RegisterStartupScript, it will render your script after all the elements in the
page (right before the form’s end tag). This enables the script to call or
reference page elements without the possibility of it not finding them in the
Page’s DOM.

Here is the rendered source
of the page when you invoke the
RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml&quot;
<head id=
"Head1"><title></title></head> 
<body>    <form name="form1"
method=
"post" action="StartupScript.aspx"
id=
"form1"<div> 
<input type=
"hidden"
name=
"__VIEWSTATE" id="__VIEWSTATE"
value=
"someViewstategibberish" /> 
</div> 
<div> 
  <span id=
"lblDisplayDate">Label</span><br
/>    <input type=
"submit"
name=
"btnPostback" value="Register
Startup Script"
id="btnPostback"
/>    <br />    <input type=
"submit"
name=
"btnPostBack2" value="Register"
id=
"btnPostBack2" /> 
</div> 
<div> 
  <input type=
"hidden"
name=
"__EVENTVALIDATION" id="__EVENTVALIDATION"
value=
"someViewstategibberish" /> 
</div>  <!–
Note
this part –>  <script
language=
‘javascript’
var lbl = document.getElementById(‘lblDisplayDate’); 
lbl.style.color=
‘red’
</script> 
</form>  <!– Note
this part –>  </body> 
</html> 

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before
any of the page elements. Since this is a direct script (not a function that
can be called, it will immediately be executed by the browser. But the
browser does not find the label in the Page’s DOM at this stage and hence you
should receive an "Object not found" error.

Here is the rendered source
of the page when you invoke the
RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml&quot;
<head id=
"Head1"><title></title></head> 
<body>    <form name="form1"
method=
"post" action="StartupScript.aspx"
id=
"form1">    <div> 
  <input type=
"hidden"
name=
"__VIEWSTATE" id="__VIEWSTATE"
value=
"someViewstategibberish" /> 
  </div>  <script language=
‘javascript’
var lbl = document.getElementById(‘lblDisplayDate’); 
// Error is thrown in the next line because lbl is null. 
lbl.style.color=
‘green’

Therefore, to summarize, you
should call the latter method if you intend to render a function definition.
You can then render the call to that function using the former method (or
add a client side attribute).

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

RegisterClientScriptBlock is
for returning blocks of client-side script containing functions.
RegisterStartupScript is for returning blocks of client-script not  
packaged in functions-in other words, code that’s to execute when the page is
loaded. The latter positions script blocks near the end of the document so
elements on the page that the script interacts are loaded before the script
runs.

,,,,,,,,,,,,,………….,,,,,,,,,,,,,,,

Code
Snip-it 1:
RegisterClientScript(

    "CS1",
    "<script language=/"javascript/">"
+
        "window.alert(
document.form[0].txtElement.value );" +
        "</script>" );

Code Snip-it 2:
RegisterClientScript(

    "CS2",
    "<script language=/"javascript/">"
+
        "function a(){window.alert(
document.form[0].txtElement.value );}" +
        "</script>" );

Code Snip-it 3:
RegisterStartupScript(

    "CS3",
    "<script language=/"javascript/">"
+
        "window.alert(
document.form[0].txtElement.value );" +
        "</script>" );

Code Snip-it 4:
RegisterStartupScript(

    "CS4",
    "<script language=/"javascript/">"
+
        "function b(){window.alert(
document.form[0].txtElement.value );}" +
        "</script>" );

OK so there are some example scripts. Now CS1 and CS3 will be executed as soon
as the web page parses them. The problem is CS1 is parsed and run before
any form element have been created by the web browser, whereas CS3 is parsed
and run after the form elements are created. So CS1 will execute and throw an
error telling you that there is craziness in the world as there is no object in
the form called txtElement, so you definitely cannot find out what its value
is.  CS3 on the otherhand will work fine as txtElement will have been
created in the form object.

CS2 and CS3 are effectively the same thing with the assumption that they are
called by some user action.

So I recommend RegisterClientScript for any functions that will be called by
user actions such as mouseovers etc.
I recomment RegisterStartupScript for any initialisation that needs to be done,
such as setting the time in a textbox based on the web browsers time. If you
are going to create a function that is called by the window.onload event then
RegisterClientStartup and RegisterStartupScript will have the same effect, just
place the script in a different part of your output HTML.

 

string
scriptCode = "<script language=javascript> window.alert(‘Account has
been modified successfully.’); window.opener.location.reload();
window.close();  </script>";

           
if (
!IsStartupScriptRegistered("clientScript"))

               
Page.RegisterStartupScript("clientScript",
scriptCode);

 

///////////////////////////////////////////////////////////

 

 

Close
Window

A close window function is useful when you use a pop-up
window on your page, as it allows the visitor to easily close the window. You
can do it several ways: To use a button, paste the following where you want the
button to appear:

<form>

<input type=button
value="Close Window" onClick="javascript:window.close();">

</form>

For a text link, paste the following where you want the link
to appear:

<a
href="javascript:window.close();">Click to Close Window</a>

To make the window close after a given number of seconds,
add the event handler to the <body> tag. FYI, 20000 equals 20 seconds.

<BODY
onLoad="setTimeout(window.close,20000)">

 

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Making Animated Buttons in JS

You need to
place the button on the page as you would any other image on a webpage. Then
you need to add a "onMouseOver" event to the image. The event causes
the browser to run a javascript function that will replace the initial image
with another image. Finally we add an "onMouseOut" event to the image
as well. This event causes the browser to run a javascript function that
inserts the initial image again when the user moves the mouse away from the
image. The technique is thus a two step process:

First, you
need to add mouse event settings to the HTML tags of the images. Second, you
need to add a script that will be performed when the browser detects the mouse
events.

view plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=making-animated-buttons-in-javascript.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=making-animated-buttons-in-javascript.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=making-animated-buttons-in-javascript.php"
?

1.                   
  

2. <Script>
  

3. button1up = new Image; buttonUp.src = "buttonUp.gif";   

4. button1down = new Image; buttonDown.src = "buttonDown.gif";   

5.   

6. function MouseOverRoutine(ButtonName)
  

7. {
  

8.  if (ButtonName=="button")   

9.  {document.button.src = buttonDown.src;}
  

10. }  

                 

<Script>

button1up = new Image; buttonUp.src =
"buttonUp.gif";

button1down = new Image; buttonDown.src =
"buttonDown.gif";

 

function MouseOverRoutine(ButtonName)

{

 if (ButtonName=="button")

 {document.button.src = buttonDown.src;}

}

Now our
button will shift from buttonUp to buttonDown when a mouseover event occurs. To
complete the script all we need to do is make the opposite function, that will
do exactly the opposite when a mouseout event occurs.

view plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=making-animated-buttons-in-javascript.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=making-animated-buttons-in-javascript.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=making-animated-buttons-in-javascript.php"
?

1. function MouseOutRoutine(ButtonName)   

2. {
  

3.   if (ButtonName=="button")   

4.   {document.button.src = buttonUp.src;}
  

5.   }
  

6. </script>  

function MouseOutRoutine(ButtonName)

{

  if
(ButtonName=="button")

  {document.button.src
= buttonUp.src;}

  }

</script>

If you want
more buttons on your page, all you need to do is double each line referring to
button and change it to button1, button2 or whatever you want to call the
buttons you might have.

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Date Objects

 

Method

Description

 

getDate()

Returns the
current date and time

 

getFullYear()

Returns the
four digit year

 

getYear()

Returns the
year in two digit format, ie 08

 

getUTCFullYear

Returns the
four digit year according to universal time.

 

getUTCYear

Returns the
year in two digit format according to universal time

 

getMonth

Returns the
month as a number, between 0 and 11

 

getUTCMonth

Returns the
month as a number according to universal time

 

getDate

Returns the
day of the month.

 

getUTCDate

Returns the
day of the month according to universal time

 

getDay()

Returns the
day of the week as a number between 0-6

 

getUTCDay()

Returns the
day of the week according to universal time

 

 

Time Objects

Method

Description

getHour()

Returns the
hour in 24-hour format

getUTCHour()

Returns the
hour according to universal time in 24 hour format

getMinute()

Returns the
minute between 0 and 59

getUTCMinute()

Returns the
minute according to universal time

getSecond()

Returns the
second between 0 and 59

getUTCSecond()

Returns the
second according to universal time

getMillisecond()

Returns the
millisecond between 0 and 999

getUTCMillisecond()

Returns the
millisecond according to universal time

getTimezoneOffset()

Returns the
difference in minutes between GMT and local time

 

 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Creating Popup Windows

There maybe
times that you do not want a user to navigate away from your site, because you
want to show them something, but still have more data that you would like to
give them. A good example of this is if you want to show them a picture for a
news story. Using JavaScript you can make the link open in a new window. We will
be using the window.open() function that is built into JavaScript. The
window.open function has a special formating that we need to look at before we
use it.
window.open(URL, Title, attributes)
To use the window.open function we have to tell it the source of our image, or
web site, the title of the new window, and then if we want to customize the
window we can pass it other attributes that the function will understand, like
toolbar=no. Here is a list of attributes that you can pass to the window.open function.

Attribue

Action

Width

This attribute will set the width of the new
window.

Height

Based on the name of this attribute, you could
have guessed correctly that this sets the height of the window.

Resizable

Like the rest of the attributes in this list,
you can set this to either yes or no. It allows the window to resized by the
user.

Scrollbars

The scrollbars attribute will show or hide the
scrollbars on the window.

Toolbar

Like the scrollbars, this will either hide or
show the toolbar of the browser. The toolbar is location where the back,
foward, reload, stop buttons are located.

Location

Location will allow you to show or not show the
url box, this is the box you type in the address of the site you want to go
to, like http://www.code-sucks.com

Directories

If directories is set to no, then it will not
show toolbars that the user has, like a Favorites toolbar.

Status

The status bar hides the bar at the very bottom
of the browser that shows how much of the page that is loaded.

Menubar

The menubar is the part of the browser that has
File, Edit, View, etc. Set this so no to hide this bar.

Copyhistory

This allows you to copy the history of the
parent window to the new window.


With the new information, lets create a function that will allow us to open web
sites, and images in new windows.

view
plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
copy to clipboardHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
?

1.   <script lanuage="JavaScript" type="text/Javascript">   

2.    function popup(lightbulb){
  

3.       popupWindow= window.open(lightbulb, "Pop Up""toolbar=no")   

4.       popupWindow.focus()
  

5.    }   

6.   </script>  

<script lanuage="JavaScript"
type="text/Javascript">

 function
popup(lightbulb){

popupWindow=
window.open(lightbulb, "Pop Up", "toolbar=no")

popupWindow.focus()

 }

</script>

Since we may
use this code again, we created a function. This will make our code appear
neater, and run faster since we do not have to rewrite all of the code, and the
browser does not have to process it. What this function does is passes a
varible to the window.open function. Then using the focus() method, we open the
new window when the link is clicked. Now when we want to open a new window, we
will just pass a varible to the function.

view
plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
copy to clipboardHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=create_popup_windows.php"
?

1.   <a href="javascript:popup(‘lightbulb_on.jpg’)">Lights On</a>  

 

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Changing Images based on Time

If you ever used
Google’s iGoogle feature, you may have noticed that depending on the hour, the
background changes. Using JavaScript we can create the same feature, which will
rotate an image based on the time that the the user visits.
Here are the three images that we are going to be using.

view plainHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=changing_images_based_on_time.php"
copy to clipboardHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=changing_images_based_on_time.php"
printHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=changing_images_based_on_time.php"
?

1. <script language="JavaScript" type="text/javascript">   

2.  var now = new Date();
  

3.  var hour = now.getHours();
  

4.   

5.  if (hour <=11){
  

6.     var TimeofDay = "<IMG src="images/morning.jpg">"  

7.  }else if(hour > 11 && hour <= 17){
  

8.     var TimeofDay = "<IMG src="images/afternoon.jpg">"  

9.  }else if(hour > 17){
  

10.     var TimeofDay = "<IMG src="images/night.jpg">"  

11.  }
  

12. </script>
  

13.   

14. <script>
  

15.     document.write(TimeofDay)
  

16. </script>  

<script language="JavaScript"
type="text/javascript">

 var now = new
Date();

 var hour =
now.getHours();

 

 if (hour
<=11){

            var
TimeofDay = "

"

 }else if(hour
> 11 && hour <= 17){

            var
TimeofDay = "

"

 }else if(hour
> 17){

            var
TimeofDay = "

"

 }

</script>

 

<script>

document.write(TimeofDay)

</script>

The first
thing we need to do in our script is to find what hour it currently is. We used
the Date() function to do this. This is nothing that we have not seen already in
earlier tutorials. We are then going to use two functions to determine what
image to display. In our script we will have any time before 11 to display a
sunrise, any time between 12 to 17 to display the afternoon image, and any time
greater then 17 to show our night sky image. Later in the body, when we want to
display the image we use the document.write, and pass the TimeofDay to it.
Below is an example of the code in action.

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Specify
Referring Page

This script makes sure that your visitor can only reach a
given page from the page that you specify. Paste the following before the
ending head tag on the page:

<SCRIPT
LANGUAGE="JavaScript">

var allowedreferrer = "http://www.yoursite.com/referringpagename.htm";

if
(document.referrer.indexOf(allowedreferrer) == -1) {

alert("You can only
access this page from " + allowedreferrer);

window.location=allowedreferrer;

}

</script>

That’s it! If you know of some other script snippets, let us
know using the comments below and we will add them to this article!

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Window
Close Automatically

 

<!–  Place this snippet in the body tag of the
popup window.

onLoad="setTimeout(‘window.close()’, 5000);"

 

 

Window
Close Method

 

<!– Paste this code into the BODY section of your HTML
document  –>

 

<button type="button"
onclick="window.close()">Close Window</button>

<p><div align="center">

<font face="arial, helvetica" size"-2">Free
JavaScripts provided<br>

by <a href="http://javascriptsource.com">The
JavaScript Source</a></font>

</div><p>

 

 

<script type="text/javascript">

<!–

var i;

i=1;

for(i=1;i<2;i++) {

  
window.open("www.javascriptsource.com")

}

//–>

</script>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

Redirect with a Timer

There maybe times
that you want to redirect a visitor on your site. In JavaScript, you can use
window.location to redirect a user to a different page. You may have seen this
used by sites with full page ads, or to redirect users to the site’s new domain
name. You can add a timer to the script that will allow the page to redirect
and the user will not need to click a link or type in the new URL.

view plainHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=redirect_with_timer.php"
copy to clipboardHYPERLINK
"http://www.code-sucks.com/code/javascript/template.php?tutorial=redirect_with_timer.php"
printHYPERLINK "http://www.code-sucks.com/code/javascript/template.php?tutorial=redirect_with_timer.php"
?

1. <script language="JavaScript" type="text/javascript">   

2. var count =6   

3. var redirect="http://www.code-sucks.com&quot;  

4.   

5. function countDown(){   

6.  if (count <=0){   

7.   window.location = redirect;
  

8.  }else{   

9.   count–;
  

10.   document.getElementById("timer").innerHTML = "This page will redirect in "+count+" seconds."  

11.   setTimeout("countDown()", 1000)
  

12.  }
  

13. }
  

14. </script>
  

15.   

16. Our webpage has moved.  Please update your bookmarks for the new site.
  

17.   

18. <span id="timer">   

19. <script>
  

20.  countDown();
  

21. </script>
  

22. </span>  

<script language="JavaScript"
type="text/javascript">

var count =6

var redirect="http://www.code-sucks.com&quot;

 

function countDown(){

 if (count
<=0){

 
window.location = redirect;

 }else{

  count–;

 
document.getElementById("timer").innerHTML = "This page
will redirect in "+count+" seconds."

 
setTimeout("countDown()", 1000)

 }

}

</script>

 

Our webpage has moved.  Please update your bookmarks for the new
site.

 

<span id="timer">

<script>

 countDown();

</script>

</span>

So the
script is redirecting the user since the site’s domain name has been changed.
The first thing the script does is set two variables, one is named count, and
the other is named redirect. We see that redirect is set to the URL that we
want the user to be redirected to, and count that is set to six. We then see a
function called countDown. Inside this function we see an if else statement. It
tells us that if count is less than or equal to zero, then we want the window
location to be the value or our redirect variable. The else part of the
function subtracts one from count, then displays the value of count, along with
the sting This page will redirect in seconds. The last part of the else sets a
timer with the setTimeout function built into JavaScript. We tell the
setTimeout function to run the countDown function every 1000 milisecond, or
every second. Below is an example of the code, but without the redirect. If you
loaded the page over five seconds ago, then just reload the page to see the
example.

The page would have redirected at this point.

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

 

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: