javascripts & jquery

51
JavaScripts & jQuery by Asanka Indrajith

Upload: asanka-indrajith

Post on 21-Jan-2017

93 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: JavaScripts & jQuery

JavaScripts & jQuery by Asanka Indrajith

Page 2: JavaScripts & jQuery

Topics Covered

▪ JavaScript Syntax.▪ Writing simple JavaScript programs.▪ Using input and output statements.▪ Basic memory concepts.▪ JavaScript operators.▪ Decision-making statements.▪ JSON▪ jQuery

Page 3: JavaScripts & jQuery

History

▪ JavaScript created by Netscape ▪ IE and Netscape/Other browsers renderings are slightly

different▪ Standardized by European Computer Manufacturers

Association (ECMA)▪ http://www.ecma-international. org/publications

/standards/Ecma-262.htm

Page 4: JavaScripts & jQuery

Why Study JavaScript?

▪ JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages

Page 5: JavaScripts & jQuery

Introduction

▪ JavaScript scripting language– Client-side scripting enhances functionality and appearance▪ Makes pages more dynamic and interactive▪ Pages can produce immediate response without contacting a server▪ Customization is possible on the basis of users’ explicit and implicit

input▪ Browser has to have a built-in (JavaScript) interpreter

– Foundation for complex server-side scripting

Page 6: JavaScripts & jQuery

JavaScript: Syntax

▪ A computer program is a list of "instructions" to be "executed" by the computer.

▪ JavaScript statements are composed of:– Values, Operators, Expressions, Keywords, and Comments.

var x = 5;var y = 6;var z = x + y;

Page 7: JavaScripts & jQuery

JavaScript: Syntax

▪ Values -Two types  – Fixed values are called literals. ▪ 1001, "John Doe"

– Variable values are called variables.▪ var x;

▪  Operators– assignment operator ( = ) to assign values to variables▪ var x = 5;

– arithmetic operators ( + - *  / ) to compute values▪ (5 + 6) * 10

Page 8: JavaScripts & jQuery

JavaScript: Syntax

▪ Expressions– combination of values, variables, and operators, which computes

to a value. ▪ 5 * 10, x * 10

▪  Keywords – used to identify actions to be perform.▪ var,  function, if, for, instanceof, new, etc

▪ Comments– double slashes // or between /* and */ is treated as a comment.

Page 9: JavaScripts & jQuery

JavaScript: Object-Based Language

▪ There are three object categories in JavaScript: Native Objects, Host Objects, and User-Defined Objects.– Native objects: defined by JavaScript. ▪ String, Number, Array, Image, Date, Math, etc.

– Host objects : supplied and always available to JavaScript by the browser environment.▪ window, document, forms, etc.

– User-defined objects : defined by the author/programmer▪ Initially, we will use host objects created by the browser

and their methods and properties

Page 10: JavaScripts & jQuery

Scripting Where To

▪ Two approaches to client side scripting:– Inline scripting▪ Written in the <body> section of a document

– JavaScript code embedded in the <head> section

▪ It is a good idea to place scripts at the bottom of the <body> element. This can improve page load, because script compilation can slow down the display.

Page 11: JavaScripts & jQuery

Scripting Where To

▪ <script> tag▪ Indicate that the text is part of a script▪ type attribute– Specifies the type of file and the scripting language use:▪ Value: “text/javascript”

▪ “language=“ for pre IE5 and NS6

<script type=”text/javascript" language=”javascript" ><!--

// ends script hiding --></script>

Page 12: JavaScripts & jQuery

General Format

<!doctype ...><html><head><Title> Name of web page </title><script type="text/javascript">...script goes here</script></head><body>...page body here: text, forms, tables...more JavaScript if needed ...onload, onclick, etc. commands here</body></html>

Page 13: JavaScripts & jQuery

 DOM (Document Object Model)

▪ An model for describing HTML documents (and XML documents)▪ A standard object model and programming interface for HTML

▪ HTML elements as object.

▪ Independent of browser, language ▪ A common set of properties/methods to access everything in a

web document.– Methods - getElementById , createElement, setAttribute,– Properties - innerHTML , title, URL, readyState ▪ is a standard for how to get, change, add, or delete HTML

elements

Page 14: JavaScripts & jQuery

DOM (Document Object Model)

Page 15: JavaScripts & jQuery

Characteristics

▪ Case sensitive▪ Object oriented – (but is not a class-based object-oriented language like

Java, C++, C#)

▪ Dynamically typed▪ Standard operator precedence▪ Overloaded operators▪ Reserved words▪ Scope rules for variables

Page 16: JavaScripts & jQuery

Characteristics

▪ Strings are very common data types▪ Rich set of methods available▪ Arrays have dynamic length▪ Array elements have dynamic type▪ Arrays are passed by reference▪ Array elements are passed by value

Page 17: JavaScripts & jQuery

JavaScript’s Uses Include:

▪ “Dynamic” web-pages– What’s DHTML? (in a second)

▪ Image manipulation– Swapping, rollovers, slide shows, etc.

▪ Date, time stuff (e.g. clocks, calendars)▪ HTML forms processing– Verifying input; writing output to fields

▪ Cookies

Page 18: JavaScripts & jQuery

What’s DHTML?

▪ Purpose: make dynamic / interactive web-pages on the client side

▪ Use of a collection of technologies together to do this, including– Markup language (HTML, XML, etc.)– Scripting language (JavaScript, etc.)– Presentation language (CSS etc.)

Page 19: JavaScripts & jQuery

1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 7.1: welcome.html --> 6 <!-- Displaying a line of text --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>A First Program in JavaScript</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 document.writeln( 15 "<h1>Welcome to JavaScript Programming!</h1>" ); 16 // --> 17 </script> 18 19 </head><body></body> 20 </html>

Page 20: JavaScripts & jQuery

1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 7.4: welcome4.html --> 6 <!-- Printing multiple lines in a dialog box --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head><title>Printing Multiple Lines in a Dialog Box</title> 10 11 <script type = "text/javascript"> 12 <!-- 13 window.alert( "Welcome to\nJavaScript\nProgramming!" ); 14 // --> 15 </script> 16 17 </head> 18 19 <body> 20 <p>Click Refresh (or Reload) to run this script again.</p> 21 </body> 22 </html>

Page 21: JavaScripts & jQuery
Page 22: JavaScripts & jQuery

Dynamic Pages

▪ A script can adapt the content based on explicit input from the user or other information– System clock: Time of day– Hidden input– Cookies

▪ User input can be collected by invoking the prompt method of a window object – This will display a dialog box that prompts user for input

Page 23: JavaScripts & jQuery

1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 7.6: welcome5.html --> 6 <!-- Using Prompt Boxes --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Using Prompt and Alert Boxes</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var name; // string entered by the user 15 16 // read the name from the prompt box as a string 17 name = window.prompt( "Please enter your name", "GalAnt" ); 18 19 document.writeln( "<h1>Hello, " + name + 20 ", welcome to JavaScript programming!</h1>" ); 21 // --> 22 </script>

Page 24: JavaScripts & jQuery
Page 25: JavaScripts & jQuery

This is the promptto the user.

This is the default value that appears when the dialog opens.

This is the text field in which the user types the value.

When the user clicks OK, the value typed by the user is returned to the program as a string.

If the user clicks Cancel, the null value will be returned to the program and no value will be assigned to the variable.

Page 26: JavaScripts & jQuery

Simple Script Example: Adding Integers

▪ The values of numbers to be added are obtained as user inputs collected through the window.prompt method

▪ parseInt– Converts its string argument to an integer– What happens if the conversion is not done?

▪ NaN (not a number): value returned if non-numerical values are passed to the paresInt method

Page 27: JavaScripts & jQuery

1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 7.8: Addition.html --> 6 <!-- Addition Program --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>An Addition Program</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var firstNumber, // first string entered by user 15 secondNumber, // second string entered by user 16 number1, // first number to add 17 number2, // second number to add 18 sum; // sum of number1 and number2 19 20 // read in first number from user as a string 21 firstNumber = 22 window.prompt( "Enter first integer", "0" ); 23

Page 28: JavaScripts & jQuery

24 // read in second number from user as a string 25 secondNumber = 26 window.prompt( "Enter second integer", "0" ); 27 28 // convert numbers from strings to integers 29 number1 = parseInt( firstNumber ); 30 number2 = parseInt( secondNumber ); 31 32 // add the numbers 33 sum = number1 + number2; 34 35 // display the results 36 document.writeln( "<h1>The sum is " + sum + "</h1>" ); 37 // --> 38 </script> 39 40 </head> 41 <body> 42 <p>Click Refresh (or Reload) to run the script again</p> 43 </body> 44 </html>

Page 29: JavaScripts & jQuery
Page 30: JavaScripts & jQuery

Functions

Page 31: JavaScripts & jQuery

Conditions

Page 32: JavaScripts & jQuery

Example

Page 33: JavaScripts & jQuery

Array object

▪ The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

▪ var fruits = new Array( "apple", "orange", "mango" );▪ var fruits = [ "apple", "orange", "mango" ];

Page 34: JavaScripts & jQuery

Array object

▪ pop() : Removes the last element from an array and returns that element.

▪ push() : Adds one or more elements to the end of an array and returns the new length of the array.

▪ reverse() : Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.

▪ slice( begin [,end] ) : extracts a section of an array and returns a new array.

▪ sort() : sorts the elements of an array.

Page 35: JavaScripts & jQuery

Date Object

▪ The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

▪ Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

▪ The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.

Page 36: JavaScripts & jQuery

Date Object

Page 37: JavaScripts & jQuery

JSON

▪ JSON stands for JavaScript Object Notation▪ JSON is lightweight data interchange format▪ JSON is language independent *▪ JSON is "self-describing" and easy to understand

Page 38: JavaScripts & jQuery

JSON

Page 39: JavaScripts & jQuery

jQuery

Page 40: JavaScripts & jQuery

What we’ll be looking at...

▪ Why jQuery?▪ jQuery fundamentals▪ Creating and manipulating elements▪ Events▪ Animations and effects▪ Using the CDN After these topics,

You‘ll say...

Page 41: JavaScripts & jQuery

jQuery is

– Most popular, cross-browser JavaScript library– Focusing on making client-side scripting of HTML simpler▪ Easy navigating the DOM▪ Handling events▪ Working with Ajax

– Open-source, released in 2006▪ Many JavaScript frameworks try bending the language

out of its natural form▪ jQuery aims at using CSS, HTML and JavaScript to

maximum advantage.

Page 42: JavaScripts & jQuery

Advantages

– Lightweight– Easy to learn using familiar CSS syntax and intuitive

– Many plugins available– Easy to extend and compatible– It’s on Microsoft’s radar– Rich community

$('#something').hide().css('background', 'red').fadeIn(); 

Page 43: JavaScripts & jQuery

jQuery fundamentals: $

▪ $ function (aka jQuery() function) returns– A JavaScript object containing an array of DOM elements– In the order they were found in the document– Matching a specified selector (for example a CSS selector)

▪ It returns the same group of elements, can be chained

$("div.someClass").show();

Finds all DIVs withClass someClass andSets them visible

$("div.someClass").show().addClass("SomeOtherClass");

To the same set, thisadds another class

Page 44: JavaScripts & jQuery

jQuery fundamentals: the ready handler

▪ Script execution should wait until DOM elements are ready– You say: window.onload?– Sadly, this waits for everything to be loaded, including images

etc– Script execution is too late

▪ Instead, we need to wait only until the DOM tree is created– Can be difficult in cross-browser situations– Easy-peasy with jQuery$(document).ready(function() { $("div.someClass").show();});

$(function() { $("div.someClass").show();});

Page 45: JavaScripts & jQuery

jQuery fundamentals: selectors

▪ At the core of jQuery lies its selector engine– Can be used to select elements based on names, attribute,

position...▪ $() is heavily overloaded– Making a selection– Creating new HTML elements

Page 46: JavaScripts & jQuery

Execute jQuery

Page 47: JavaScripts & jQuery

jQuery fundamentals: selectors

▪ Can be used to select elements based on names, attribute, position.

▪ Most basic: CSS selectors$("p a.someClass")

– Can be combined$("p a.someClass, div")

▪ Child selector$("ul.someList > li > a")

Page 48: JavaScripts & jQuery

jQuery fundamentals: selectors

▪ Attribute selector$("a[href*='http://www.snowball.be']")$("span[class^='some']")$("span[class]")

▪ Position$("a:first")$("div:even")$("table#someTable td:first-child")

Psuedo-classes (CSS state of an element.)

$("input:checked")

$("input:not(:checked)")

Page 49: JavaScripts & jQuery

More selectors

Full list at http://www.w3.org/TR/css3-selectors/

Page 50: JavaScripts & jQuery

Good Practices

▪ Use Object based coding<script>var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; }};$(“#demo").text(person.fullName);</script>

Page 51: JavaScripts & jQuery

Exercise

▪ Using jquery ajax, show current weather of the location. – Use http://openweathermap.org/current to get data– Add textbox to type the location– Add button to invoke ajax request– Come up your own idea to show the result. – Try to use only jquery without using pure javascript to do this

exercise.