Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions."— Presentation transcript:

1 Getting Started

2 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



5 Cross browser : IE / FireFox / Safari / Opera /Chrome CSS-like syntax – easy for developers/non- developers to understand Lightweight (compressed version) Active developer community Extensible - plugins 5

6 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! Dont turn every project into a quest to jQuery-ize the problem, use jQuery where it makes sense. Create solutions in environments where they belong.

7 jQuery Javascript

8 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

9 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


11 Similar to CSS - multiple options (notice: type='text/javascript' NOT required in HTML5): Include external.js file via: Include in the tag Our Javascript Code Goes Here Include in the tag document.write("Let's write some HTML right here!"); Include as an event

12 Similar to CSS - the less 'inline' the better. (Generalization) Downright Bad: Include as an event Even Less Good: Include in the tag Less Good: Include in the tag Best: Include external.js file

13 Be able to read and understand some JavaScript Be able to manipulate documents with jQuery

14 JavaScript is a big, complex language These powerpoints will only scratch the surface Its 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 arent designed to report errors Dont expect to get any helpful error messages Write and test your programs a little bit at a time

15 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

16 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

17 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

18 // String var name = John; // Integer(number) var age = 30; // Array var children = [Jane, Jimmy]; // Boolean var 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

19 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. Youve 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. OperatorEnglishExample +Addition2 + 4 -Subtraction6 - 2 *Multiplication5 * 3 /Division15 / 3 %Modulus43 % 10 example 7example 8 OperatorEnglish ++Pre/Post Increment --Pre/Post Decrement

20 <!-- definition of variables var num_car= 25; var passenger_per_car= 3; //calculation of total number of people var total_passenger= num_car * passenger_per_car alert(total_passenger); // end of script -->

21 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. OperatorEnglishExampleResult ==Equal Tox == yfalse !=Not Equal Tox != ytrue <Less Thanx < ytrue >Greater Thanx > yfalse <=Less Than or Equal To x <= ytrue >=Greater Than or Equal To x >= yfalse example 10 example 12

22 Logical Operators The logical operators perform logical operations on variables. OperatorEnglishExample &&Logical AND (x 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;

23 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) Dont rely on it! For clarity, use parentheses

24 Its possible to combine operations in a conditional statement. For example: to find out if a certain variable, lets 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.

25 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.*/

26 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; Heres the first index and element: beatles[0] = "John"; It might seem counterintuitive to start with an index of zero instead of one, but thats 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

27 var score = new Array(3); score[0] = 35 score[1] = 56 score[2] = 10 Alternative : var score = new Array(35,56,10); sum=score[0]+score[1]+score[2]; alert(sum) ;


29 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.

30 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

31 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

32 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

33 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.

34 Diagnostic messages indicate flow of control 1. var variable1 = 1; var variable2 = 2; 2. 3. if(variable1 >= 0){ 4. document.write( 1 is greater than 0 "); 5. } 6. document.write( Resuming execution after 'if' 7. statement "); 8. 9. if(variable1 > variable2){ 10. document.write( 1 is greater than 2 "); 11. } 12. else { 13. document.write( 2 is greater than 1 "); 14. } 15. document.write("Resuming execution after 'if/else statement ");


36 The if statement is probably the most important and useful conditional statement. The only drawback to the if statement is that it cant 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, youll 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

37 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

38 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

39 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. Heres an example of a while loop: var count = 1; while (count < 11) { alert (count); count++; } /* Its 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 didnt increase the value of the count variable, the while loop would execute forever. */


41 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 functions return value Where to put JS functions in your webpage

42 function alertName() { alert(Hello John); } // Accept arguments function alertName(name) { alert(Hello + name); } // Call the function alertName(John); //Hello John // Function assignment var alertName = function(name) { alert(Hello + name); } // Call the function alertName(John); //Hello John

43 <!– function popup() { alert("Hello World") } //--> 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

44 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)

45 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. Heres 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);

46 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?

47 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!!!

48 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

49 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

50 If needed, you can declare local variables within a function local variable is visible only within the function body after its declared Commonly used to store results of an intermediate calculation

51 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

52 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);


54 In JavaScript, objects are pairs of keys and values (in other languages this structure might be called a hash or a dictionary). // Empty object var 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.

55 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( + is + this.age); } }; person.introduceYourself(); //John is 30

56 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.

57 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.

58 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' });


60 jQuery is DOM scripting The DOM is your html document code. From the to the The DOM is "ready" when everything on the page has loaded. Stylesheets JavaScripts Images

61 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. Wikipediacross-platformlanguageobjects HTMLXHTMLXML You can add and subtract DOM elements on the fly You can change the properties and contents of DOM elements on the fly

62 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

63 Get it @ 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.

64 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.

65 $(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

66 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

67 Html: The sky is blue Script: $(function(){ $("p").addClass("isBlue"); //make font in paragraph blue }); Resulting html: p>The sky is blue

68 $(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.addClass("isBlue"); Built in method that adds a class to the jQuery Collection Class is in quotes. ends with a semicolon.

69 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.

70 Uses the same syntax you use to style elements in CSS! $("p") $("div") $("#foo") id="foo" $(".foo") class= "foo"

71 ID selector. Find DOM element by ID. ID selector Syntax: $("#myDiv") selects element with ID myDIV. ID search requires # to be preFixed. Element selector: Find all DOM element by element Type. Element selector: Syntax: $("div") selects all DIV in the dom tree. Notice no prefix used. CSS selector: Find all element with a CSS class. CSS selector: 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 : 71

72 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. $(document).ready(function() { alert(Welcome to JQuery); }); jQuery

73 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

74 jQuery: $("p").addClass("sophisticated"); Before: After:

75 jQuery: $("p").removeClass("sophisticated"); Before: After:

76 Show a hidden wrap an element with.wrap(" ") Select parent.parent("p") Get/Set innerHTML.html() Get/Set Value.val()

77 jQuery: $("div").show(); Before: After:

78 jQuery: $("#eric").text("Is Cool"); Before: Is Lame After: Is Cool

79 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

80 jQuery abstracts Etc… Attached via selectors $( ).eventname( or inline); $("a").click(function(){ $(this).addClass(red);});

81 .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

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

83 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

84 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.

85 – jQuery homepage – jQuery tutorial blog – jQuery documentation – jQuery user interface 85

Download ppt "Getting Started. jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions."

Similar presentations

Ads by Google