javascripts & jquery
TRANSCRIPT
JavaScripts & jQuery by Asanka Indrajith
Topics Covered
▪ JavaScript Syntax.▪ Writing simple JavaScript programs.▪ Using input and output statements.▪ Basic memory concepts.▪ JavaScript operators.▪ Decision-making statements.▪ JSON▪ 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
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
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
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;
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
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.
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
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.
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>
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>
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
DOM (Document Object Model)
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
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
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
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.)
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>
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>
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
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>
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.
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
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
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>
Functions
Conditions
Example
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" ];
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.
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.
Date Object
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
JSON
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...
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.
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();
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
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();});
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
Execute 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")
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)")
More selectors
Full list at http://www.w3.org/TR/css3-selectors/
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>
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.