getting started. jquery is a fast and concise javascript library that simplifies html document...

85
jQuery Getting Started

Upload: freddy-evers

Post on 31-Mar-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQueryGetting Started

Page 2: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

What is Jquery

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

jQuery is designed to change the way that you write JavaScript.

2

Page 3: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Trends

Page 4: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Trends

Page 5: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Advantages

Cross browser : IE / FireFox / Safari / Opera /Chrome

CSS-like syntax – easy for developers/non-developers to understand

Lightweight (compressed version)

Active developer community

Extensible - plugins5

Page 6: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

What jQuery is not…

A substitute for knowing JavaScript jQuery is very useful, but you should still know how

JavaScript works and how to use it correctly. This means more than Googling a jQuery/JavaScript tutorial and calling yourself an expert.

The answer to every problem There is still plenty of functionality built into

JavaScript that should be utilized! Don’t turn every project into a quest to ‘jQuery-ize’ the problem, use jQuery where it makes sense. Create solutions in environments where they belong.

Page 7: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery is a subset of Javascript

jQuery

Javascript

Page 8: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

5 Things jQuery Provides

Select DOM (Document Object Model) elements on a page – one element or a group of them

Set properties of DOM elements, in groups (“Find something, do something with it”)

Creates, deletes, shows, hides DOM elements

Defines event behavior on a page (click, mouse movement, dynamic styles, animations, dynamic content)

AJAX calls

Page 9: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

What pieces of Javascript do we need to understand?

Strings and numbers - basic pieces of information

Variables - where to store pieces of information

Functions - how to call reusable pieces of code

Callbacks - functions that get called in response to something else

Arrays - store a list of values (like a list of variables)

Objects - understand a little bit about these

Conditionals - controlling what parts of a program executes

Page 10: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

A Little Demo

Page 11: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Where does Javascript go?

Similar to CSS - multiple options (notice: type='text/javascript' NOT required in HTML5):

Include external .js file via: <script

src='file.js'></script>

Include in the <head> tag <script> Our Javascript Code Goes

Here </script>

Include in the <body> tag <script> document.write("Let's write

some HTML right here!"); </script>

Include as an event <a href='javascript:void(0);'

onclick='alert("Hello World!");'>

Page 12: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Where do we prefer?

Similar to CSS - the less 'inline' the better. (Generalization)

Downright Bad: Include as an event Even Less Good: Include in the <body> tag Less Good: Include in the <head> tag Best: Include external .js file

Page 13: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Goals

Be able to read and understand some JavaScript

Be able to manipulate documents with jQuery

Page 14: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Warnings 

JavaScript is a big, complex language These powerpoints will only scratch the surface It’s easy to get started in JavaScript, but if you need to

use it heavily, plan to invest time in learning it well Write and test your programs a little bit at a time

JavaScript is not totally platform independent Expect different browsers to behave differently Write and test your programs a little bit at a time

Browsers aren’t designed to report errors Don’t expect to get any helpful error messages Write and test your programs a little bit at a time

Page 15: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Statements

A script written in JavaScript, or any other programming language, consists of a series of instructions called statements.

These statements must be written with the right syntax in order for them to be interpreted correctly.

You can simply separate statements by placing them on different lines:

first statement second statement

Page 16: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Comments

Statements that are ignored (not executed) by the JavaScript interpreter are comments. Comments help you keep track of your code.

JavaScript allows you to indicate a comment in a number of different ways. Two forward slashes, must put the slashes at the start of each

comment line // Note to self: comments are good.

Comment out multiple lines A forward slash and an asterisk at the start of the comment

block and an asterisk and forward slash at the end: /* Note to self: comments are good */

HTML-style comments, but only for single lines <!— This is a comment in JavaScript.-->

Page 17: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Variables

A variable is a place in the computers memory where information (values) are stored.

A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.

You access the value in the storage place by its variable name.

Should declare variables before they are used in a script. Syntax: var is a keyword var identifyer = …;

Giving a value to a variable is called assignment. Assignment ‘looks like’ equal sign but does NOT behave like it

subTotal = subTotal + 1.50 subTotal ‘is assigned the value’ that is currently in subTotal plus the value of 1.50

Page 18: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Variables

// Stringvar name = ‘John’;

// Integer(number)var age = 30;

// Arrayvar children = [‘Jane’, ‘Jimmy’];

// Booleanvar isMarried = true;

The names of variables, along with just about everything else in JavaScript, are case-sensitive.

Variable names may include a-zA-Z0-9_$ as valid characters

Page 19: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Operations

Operations In order to do anything useful with JavaScript, we need to be able to do

calculations and manipulate data - perform operations.

Operators are symbols that JavaScript has reserved for performing operations. You’ve already seen one operator in action: the equals sign (=) to perform assignment.

JavaScript Arithmetic Operator Chart

Modulus % is just a special way of saying "finding the remainder". 43 % 10 would equal 3.

Operator English Example

+ Addition 2 + 4

- Subtraction 6 - 2

* Multiplication

5 * 3

/ Division 15 / 3

% Modulus 43 % 10 example 7

example 8

Operator English

++ Pre/Post Increment

-- Pre/Post Decrement

Page 20: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Example

<script language=“JavaScript”>

<!-- definition of variablesvar num_car= 25;var passenger_per_car= 3;

//calculation of total number of peoplevar total_passenger= num_car * passenger_per_car

alert(total_passenger);

// end of script -->

</script>

Page 21: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Operations

Comparison Operators

Comparisons are used to check the relationship between variables and/or values. A single equal sign sets a value while a double equal sign (==) compares two values. Comparison operators are used inside conditional statements and evaluate to either true or false.

Operator English Example Result

== Equal To x == y false

!= Not Equal To x != y true

< Less Than x < y true

> Greater Than x > y false

<= Less Than or Equal To

x <= y true

>= Greater Than or Equal To

x >= y false

example 10

example 12

Page 22: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Operations

Logical Operators

The logical operators perform logical operations on variables.

Operator English Example&& Logical AND (x < 10 && y > 1) is

true|| Logical OR (x==5 || y==5) is false! Logical NOT !(x==y) is true?: Ternary Operator condition ? result1 :

result2;.Result1 is called if the condition is satisfied else result2 is called.

var b=5;(b == 5) ? a="true" : a="false“;

Page 23: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Operations & Expressions

An expression is a statement that describes a computation

Usually look like algebra formulas total = subTotal * taxRate

Operators (+, -, *, /, etc.) have different levels of precedence, similar to algebra (My Dear Aunt Sally <– order of operations)

Don’t rely on it! For clarity, use parentheses

Page 24: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Operations

It’s possible to combine operations in a conditional statement.

For example: to find out if a certain variable, let’s call it num, has a value between five and ten. Two operations should be performed. First, find out if the variable is greater than or equal to five, and next find out if the variable is less than or equal to ten.

These operations are called operands.

AND Example:if ( num>=5 && num<=10 ) {alert("The number is in the right range.");}//The AND operator, represented by two ampersands (&&), both operations must be true for the

alert.

Page 25: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Operations

OR Example:if ( num > 10 || num < 5 ) {alert("The number is not in the right range.");}/* The OR operator, represented by two vertical pipe symbols (||). The OR operation

will be true if one of its operands is true. It will also be true if both of its operands are true. It will be false only if both operands are false. */

NOT Example:if ( !(1 > 2) ) {alert("All is well with the world");}/*The NOT operator, represented by a single exclamation point (!). The NOT operator

works on just a single operand. Whatever Boolean value is returned by that operand gets reversed. If the operand is true, the NOT operator switches it to false.*/

Page 26: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Data types: Arrays

Adding elements to an array is called populating. When you populate an array, you specify not just the value of the element, but also where the element comes in the array. This is the index of the element. Each element has a corresponding index. The index is contained in square brackets:

array[index] = element;

Here’s the first index and element: beatles[0] = "John";

It might seem counterintuitive to start with an index of zero instead of one, but that’s just how JavaScript works.

Declare and populate the entire beatles array: var beatles = Array(4); beatles[0] = "John"; beatles[1] = "Paul"; beatles[2] = "George"; beatles[3] = "Ringo";

You can now retrieve the element “George” in your script by referencing the index 2 (beatles[2]).

example 4

Page 27: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Example: Arrays

var score = new Array(3);

score[0] = 35score[1] = 56score[2] = 10

Alternative : var score = new Array(35,56,10);

sum=score[0]+score[1]+score[2];

alert(sum) ;

Page 28: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Control Structures

Page 29: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Conditional statements

The real power of a script is its ability to make decisions based on the criteria it is given.

Decisions are made by using conditional statements.

When a browser is interpreting a script, statements are executed one after another. You can use a conditional statement to set up a condition that must be successfully evaluated before more statements are executed.

Page 30: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Conditional statements

if statement if...else statement if...else if....else statement

The condition is contained within parentheses. The condition always resolves to a Boolean value, which is either true or false.

If statements: if (condition) statement; if (condition) statement; else statement; if (condition) statement; else if statement; else statement;

example 13

Page 31: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Conditional Statements--if

if (some boolean expression is true){

execute the statements within the curly braces, otherwise skip to the

first statement after the closing brace

}Resume execution here in either case

Page 32: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Conditional Statements– if/else

if (some boolean expression is true){

execute these statements, otherwise skip to ‘else’ clause

}else { execute these statements if boolean

expression is false}Resume execution here in either case

Page 33: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Selection (choosing alternatives)

33

if (statement in brackets is true) {Do stuff in curly braces}

else if (statement in brackets is true) {Do stuff in curly braces}

else if . . . else {Do stuff in curly braces}

Note that the first ‘if’ has no ‘else’ and the last ‘else’ has no ‘if’! Use of else is strictly optional.

Page 34: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Conditional Test Program

Diagnostic messages indicate flow of control

1. var variable1 = 1; var variable2 = 2;2. 3. if(variable1 >= 0){ 4. document.write(“<p> 1 is greater than 0 </p>"); 5. }6. document.write(“<p>Resuming execution after 'if' 7. statement</p>"); 8. 9. if(variable1 > variable2){ 10. document.write(“<p>1 is greater than 2</p>"); 11.} 12.else { 13. document.write(“<p>2 is greater than 1</p>"); 14.}

15.document.write("Resuming execution after 'if/else‘ statement</p>");

Page 35: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Looping/Repetition

Page 36: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Looping statements

The if statement is probably the most important and useful conditional statement. The only drawback to the if statement is that it can’t be used for repetitive tasks. The block of code contained within the curly braces is executed once.

If you want to execute the same code a number of times, you’ll need to use a looping statement. Looping statements allow you to keep executing the same piece of code over and over.

There are a number of different types of looping statements, but they all work in much the same way. The code within a looping statement continues to be executed as long as the condition is met. When the condition is no longer true, the loop stops.

review example 10

Page 37: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Looping statements

for The for loop is a convenient way of executing

some code a specific number of times:

for (initial condition; test condition; alter condition) {statements;}

for (var count = 0 ; count < beatles.length; count++ ) {alert(beatles[count]);}// count starts at zero, while count is less than the total amount of items in the

beatles array,// add one to the value of count (increment count ).

review example 10

Page 38: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Looping statements

for One of the most common uses of the for loop is to act on

every element of an array. This is achieved using array.length, which provides the number of elements in array:

var beatles = array("John","Paul","George","Ringo");for (var count = 0 ; count < beatles.length; count++ ) {alert(beatles[count]);}

If you run this code, you will see four alert messages, one for each Beatle. review example

10

Page 39: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Looping statements

while The while loop is very similar to the if statement. The syntax is the same:

while (condition) {statements;}

The only difference is that the code contained within the curly braces will be executed over and over as long as the condition is true. Here’s an example of a while loop:

var count = 1;while (count < 11) {alert (count);count++;}/* It’s important that something happens within the while loop that will affect the test condition.

In this case, we increase the value of count within the while loop. This results in the condition evaluating to false after ten loops. If we didn’t increase the value of the count variable, the while loop would execute forever. */

Page 40: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Functions

Page 41: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Functions

What's a Function? A function is a piece of code that sits

dormant until it is referenced or called upon to do its "function". In addition to controllable execution, functions are also a great time saver for doing repetitive tasks.

Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. This benefit is also known as "code reusability".

The syntax for defining a function:

function name(list of arguments/parameters) {

statements;}

Key issues about using functions Naming functions Passing in parameters Using local variables

within functions How to call (i.e., invoke)

functions How to handle a

function’s return value Where to put JS

functions in your webpage

Page 42: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Functions

function alertName() {alert(‘Hello John’);}

// Accept argumentsfunction alertName(name) {alert(‘Hello ‘ + name);}

// Call the functionalertName(‘John’); //Hello John

// Function assignmentvar alertName = function(name) {alert(‘Hello ‘ + name);}

// Call the functionalertName(‘John’); //Hello John

Page 43: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Functions

<html> <head> <script

type="text/javascript"> <!– function popup() { alert("Hello World") } //--> </script> </head> <body> <input type="button"

onclick="popup()" value="popup">

</body> </html>

function shout() {var beatles =

Array("John","Paul","George","Ringo");

for (var count = 0 ; count < beatles.length; count++ ) {

alert(beatles[count]);}}

This function performs the loop that pops up the names of each Beatle. Now, whenever you want that action to occur later in your script, you can invoke the function by simply writing shout();

example 9 review example 10

Page 44: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions -- Parameters

Passing parameters to the function Parameters provide functions with input Implicitly declared variables that can be

accessed by code within function body You provide actual input values when you call the

function Parameters are named variables separated by

commas

Example,function findMaxValue(num1, num2, num3)

Page 45: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Functions

You can define a function to take as many parameters/arguments as you want by separating them with commas.

Any arguments that are passed to a function can be used just like regular variables within the function.

Here’s a function that takes two parameters/arguments. If you pass this function two numbers, the function will multiply them:

function multiply(num1,num2) {

var total = num1 * num2;alert(total);}

You can invoke the function from anywhere in your script, like this:multiply(10,2);

Page 46: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions -- Calling To call a function from your program, add a

statement that contains the function name with values for the parameters the function requires

Example:var x = 1, y = 4, z = 2;

findMaxValue(x, y, z);

What value does the function return? What happens with the result?

Page 47: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions – Parameter Sequence

When calling functions, must enter parameters in same order as specified in function argument list.

1. function calculateDensity(height, width, depth, mass){

2. var volume = height * width * depth;3. var density = mass / volume;4. return density;5. }6. ……………………………………………….7. var hth = 2, wth = 3, dth = 4, mass = 10;

8. var result = calculateDensity(2, 10, 3, 4);9. //returns .07 but correct answer is .42!!!

Page 48: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Variable Scope

var name = ‘John’;

function myFunction() {alert(‘Name is: ‘ + name);}...myFunction(); //Name is John

var name = ‘John’;

function myFunction() {var name = ‘Jim’;alert(‘Name is: ‘ + name);}...myFunction(); //Name is Jim

Page 49: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions – Global Variables

Global variables are those declared outside of functions

Global variables are ‘visible’ from anywhere in the program, including inside functions

var globalHello = “Hello!”;

function writeHello() { document.write(globalHello); } // outputs “Hello!”

Example program

Page 50: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions – Local Variables

If needed, you can declare local variables within a function

local variable is visible only within the function body after it’s declared

Commonly used to store results of an intermediate calculation

Page 51: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions – Local Variables

function findMaxValue(num1, num2,num3) { var tempMax; //local var

if (num1 >= num2) { tempMax = num1; }

else { tempMax = num2; }

if(num3 >= tempMax) { tempMax = num3; }

return tempMax;

} //end function

Page 52: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JavaScript Functions -- Return Return keyword tells function to return some value and

exit immediately

Normally used to return the final result of a calculation to the calling program Usually return value is assigned to a variable

For an example, see findMaxValue function

Code snippet var x = 1, y = 4, z = 2;

var maxNumber = findMaxNumber(x, y, z);

document.write(“The maximum is: “ + maxNumber);

Page 53: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Objects

Page 54: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Objects

In JavaScript, objects are pairs of keys and values (in other languages this structure might be called a hash or a dictionary).

// Empty objectvar person = { };

// Object-hash may contain key/values

var person = {name: ‘John’,age: 30,children: [‘Jane’, ‘Jimmy’],isMarried: true};

The object created has several properties: name, age, children and isMarried.

It is created using the "object literal syntax" — that is, by putting a set of key-value pairs in { }.

Note that, for each pair, there is a colon between the key and the value, and there is a comma between each pair.

Accessing properties

We've stored our object in a variable named person, which makes it easy to access its properties.

Page 55: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Object methods

Methods of an object are just properties whose values are functions.

Add an .introduceYourself() method to the person object:

var person = {name: ‘John’,age: 30,introduceYourself: function() {

alert(this.name + ‘ is ‘ + this.age);}

};

person.introduceYourself(); //John is 30

Page 56: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

What is ‘this’?

In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used in methods to refer to the object on which a method is being called/invoked.

‘This’ refers to the object that is the context in which the method/function was called.

When we call person.introduceYourself(), the context object is person itself. This means that we can use this to access a property of the person object from directly within the .introduceYourself() method.

Page 57: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery’s this

There are really two main contexts of ‘this’ in jQuery. The first refers to a DOM element, and the second to a jQuery object.

Example of this as a DOM element ‘this’ is a DOM element when you are inside of a callback

function, for example, being called by the click, each, bind, etc. methods.

Example of this as a jQuery object 'this' is a jQuery object when you are inside your own

jQuery functions. Note that the result of a selector query (i.e. $('a') ) is a jQuery object, which is an array of the matched DOM elements

* Remember the context of 'this' changes when moving in and out of object methods.

http://www.learningjquery.com/2007/08/what-is-this

Page 58: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Objects in jQuery

There is a lot more to objects, but you now know the basics. In basic jQuery, you mainly use objects to provide configuration options. For example, you can provide an object to change several CSS properties on an element at once:

$('#main').css({ color: 'red', border: '1px solid blue' });

Page 59: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

DOM

Page 60: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

The DOM

jQuery is “DOM scripting”

The DOM is your html document code.

From the <!DOCTYPE> to the </html>

The DOM is "ready" when everything on the page has loaded.

• Stylesheets• JavaScripts• Images

Page 61: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

The DOM

“The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use.” Wikipedia

You can add and subtract DOM elements on the fly

You can change the properties and contents of DOM elements on the fly

Page 62: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

DOM Ready

In order to make sure that jQuery can find the element you asked it for, your browser needs to have loaded it (the DOM needs to be ready).

Q. How can I be sure my code runs at DOM ready?

A. Wrap all your jQuery code with the document ready function:

$(document).ready(function(){// insert jQuery code here…

});

Or

Page 63: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery Library

Get it @ www.jquery.com Installation – download the appropriate

jquery.js file and put it in a folder

jQuery 1.9 will be the last edition to support legacy editions of Internet Explorer.

jQuery 2.0 will no longer support IE6, 7 and 8.

Page 64: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery Library

jQuery 1.9 will continue to be developed and support the older IEs.

To support older versions you can use a conditional comments, e.g.

<!--[if lt IE 9]> <script src="jquery-1.9.0.js"></script><![endif]--><!--[if gte IE 9]><!--> <script src="jquery-2.0.0.js"><</script><!--<![endif]-->

Page 65: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery Syntax

$(selector).function(…) or $.function(…) or $(selector).function1(…).function2(…).functionN(…);

$() or jQuery() JQuery objects are created by jQuery() or $() jQuery object is a wrapper for a selected node or group of DOM

nodes $(“p”) is a JQuery object containing all the “p” elements in the

document

selector reference to an element or many different elements on

in a document

Function - any jQuery supported method or plugin. (…) refers to function parameters Functions can be chained in sequence

Page 66: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Decoding $$$$$$

By default, jQuery uses "$" as a shortcut for "jQuery“

$ is nothing but a shorthand notation for find method in JQuery. You can also use Jquery("") instead of $ ("") however use $ as it will be consistent.

$ accepts search selector. There are many search selectors which help in finding elements in DOM tree.

$ returns array of elements.66

Page 67: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Example

Html:<p>The sky is blue</p>

Script:$(function(){

$("p").addClass("isBlue");//make font in paragraph blue

});

Resulting html:<p class="isBlue"> p>The sky is blue </p>

Page 68: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Example

$(function(){ // = $(document).ready(function(){

});

$

Initiates the

jQuery function

$ =

jQuery

("p")

Grabs a DOM element using a CSS selector.

Selector is in quotes.

Creates a jQuery “Collection”

<p>

.addClass("isBlue");

Built in method that adds a class to the jQuery Collection

Class is in quotes.

ends with a semicolon.

Page 69: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

What is a selector?

Think CSS!

jQuery has a built in DOM transversal engine.

$(selector) returns a list of elements on the page that match the “selector”.

Example: $(“input”) will return a list of ALL input elements on the page.

Page 70: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Uses the same syntax you use to style elements in CSS!

$("p")

<p>

$("div")

<div>

$("#foo")

id="foo"

$(".foo")

class="foo"

api.jquery.com/category/selectors/

Example

Page 71: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Basic Search Selector

ID selector. Find DOM element by ID. Syntax: $("#myDiv") selects element with ID myDIV.

ID search requires # to be preFixed.

Element selector: Find all DOM element by element Type. Syntax: $("div") selects all DIV in the dom tree. Notice no prefix used.

CSS selector: Find all element with a CSS class. Syntax: $(".myClass") select all element with myClass. CSS class requires a dot.

You can also mix and match. $(“div.main”) // tag and class

$(“table#data”) // tag and id

$(“#content, .menu”) // find by id + by class

$(“h1, h2, h3, div.content”) // multiple combination Read : http://docs.jquery.com/Selectors

71

Page 72: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Using JQuery

Just add reference to Jquery JavaScript file from anywhere in your code.

Document.Ready is used to attach events and many other things using JQuery.

<html><head> <script type="text/javascript"

src="path/to/jquery.js"></script>

<script type="text/javascript"> $(document).ready(function(){ alert(“Welcome to JQuery”);}); </script> </head> <body> <a

href="http://jquery.com/">jQuery</a>

</body> </html>

Page 73: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Document Ready enclosure

Document -> Ready is equivalent to body onload method and is executed when entire page and resources have been loaded in the DOM.

If you run the above code you will get a Javascript alert box on document load.

Look at the structure of the document.ready, it accepts a method as a parameter.

Look between the method braces

$(document).ready(function()

{ alert(“Welcome to JQuery”);});

function(){ alert(“Welcome to JQuery”);}

73

Page 74: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery:$("p").addClass("sophisticated");

Before:<p>

After:<p class="sophisticated">

Example

Page 75: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

This <p> Has No Class At All!

jQuery:$("p").removeClass("sophisticated");

Before:<p class="sophisticated">

After:<p class="">

Page 76: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Some Basic Methods

• Show a hidden element.show()

• wrap an element with <a>

.wrap("<a></a>")

• Select parent <p>.parent("p")

• Get/Set innerHTML.html()

• Get/Set Value.val()

api.jquery.com/

Page 77: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

<div> Hide and Seek

jQuery:$("div").show();

Before:<div style="display:none;">

After:<div style="display:block;">

Page 78: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

jQuery:$("#eric").text("Is Cool");

Before:<p id="eric">Is Lame</p>

After:<p id="eric">Is Cool</p>

Example

Page 79: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Event handling

Events in Jquery are bound to elements inside the document.ready method. The elements get bound when document.ready is fired.

$("a").click has 2 parts. 1st selector , 2nd event.

The 1st part finds the element on which method is to be attached

The 2nd part attaches a method to the given event , in this example a Click.

$(document).ready(function(){ $("a").click(function(){alert("Thanks for visiting!"); }); });

Read: http://docs.jquery.com

Page 80: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

JQuery Events

jQuery abstracts events .click() .blur() .focus() .change() Etc…

Attached via selectors

$(<select0r>).eventname(<functionpointer> or inline);

$("a").click(function(){$(this).addClass(‘red’);});

Page 81: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Other JQuery Effects

.css(‘property’, ‘value’) .css({‘prop1’:‘value1’, ‘prop2’:’value2’…}) E.g. .css(‘color’, ‘red’)

$(“div”).show(); // just show

$(“div”).show(“slow”); // reveal slowly, slow=600ms

$(“div”).hide(“fast”); // hide fast, fast=200ms

$(“div”).toggle(100); // hide or show in 100ms

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

$(“div”).slideToggle(1000);

$(“div”).fadeIn(“fast”);

$(“div”).fadeOut(“normal”);

$(“div”).fadeTo (“fast”, 0.5); // fade to a custom opacity

Page 82: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

$("p").addClass("sophisticated").text("Hello World!").show();

Method Chaining

Page 83: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Considerations

Jquery can have performance implication dependent on how you write code.

Generalization is good but excess is bad. Remember every $/Find search using attribute /element ,parses the DOM for elements and excessive use can cause the browse to hang.

Use ID selector as much as possible or at least use nested selector using the ID as parent. To search all input element $("input") will perform slower than $("#tableName input") which will be faster.

Use JQuery methods only to change properties , get values and modify attribute s, to avoid cross browser issues.

Remember JQuery offers abstraction to provide a common interface for all cross browser method and members.

83

Page 84: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

What is Firebug?

Firebug is an extension for the Mozilla Firefox browser that allows you to debug and inspect HTML, CSS, the Document Object Model (DOM) and JavaScript.

There is also Firebug Lite for other browsers.

http://www.getfirebug.com

Page 85: Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions

Useful jQuery links

www.jquery.com – jQuery homepage

www.learningjquery.com – jQuery tutorial blog

www.visualjquery.com – jQuery documentation

http://ui.jquery.com – jQuery user interface

85