Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Programming Introduction to JavaScript 1. The growth of the WWW has resulted in a demand for dynamic and interactive websites. There are many different.

Similar presentations


Presentation on theme: "Web Programming Introduction to JavaScript 1. The growth of the WWW has resulted in a demand for dynamic and interactive websites. There are many different."— Presentation transcript:

1 Web Programming Introduction to JavaScript 1

2 The growth of the WWW has resulted in a demand for dynamic and interactive websites. There are many different kinds of scripting languages – JavaScript, … This lecture aims at offering in‐depth knowledge of JavaScript, discussing the complexity of scripting and studying various common examples. 2 Introduction

3  Client-side language.( run in the client browser)  Scripting language. (interpreted in run-time)  Not compile like other language (C#, C++, VB.Net etc).  JavaScript code can be inserted directly in the HTML or can place it in a separate file with the.js extension and link the web page with the.js file.  Use in web browser for making a website more dynamic.  Supported by Netscape 2+, Internet Explorer 3+, Opera 3+ and most of the other modern web browsers.  Contains variable, array,object,operators and function. 3 What is JavaScript ?

4 What is JavaScript JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, which was later renamed to LiveScript, and finally to JavaScript A lightweight programming language that runs in a Web browser JavaScript is a Client Side Scripting Language. Also known as ECMAScript Interpreted, not compiled. JavaScript Syntax are similar to C and Java Language. JavaScript code is usually embedded directly into HTML pages JavaScript is reasonably platform-independent

5 JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate input data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies What Can JavaScript Do?

6  Used to perform operations that would otherwise encumber the server, like form validation input.  Can be easily used to interact with HTML elements such as validate text fields, disable buttons, validate forms, or change the background color of page.  Create dynamic page  React to events such as the user enter name whenever the page load for 1 st time. User can use entered value for welcome page. 6 More usage of JavaScript

7 When you need to access other resources. Files Programs Databases When you are using sensitive or copyrighted data or algorithms. Your JavaScript code is open to the public. When not to use JavaScript

8 Java and JavaScript are two completely different languages in both concept and design! JavaScript has some features that resemble features in Java: JavaScript has Objects and primitive data types JavaScript has qualified names; for example, document.write("Hello World"); JavaScript has Events and event handlers Exception handling in JavaScript is almost the same as in Java JavaScript has some features unlike anything in Java: Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way JavaScript is an interpreted language but java is both interpreted and compiled JavaScript is not Java

9 Java VS JavaScript JavaJavaScript Sun MicrosystemsNetscape Much larger and advanced set of commands. Much smaller and simpler set of commands. Applets distinct from HTML (accessed from HTML pages). Code integrated with, and embedded in, HTML. Variable data types must be declared (strong typing). Variable data types not declared (loose typing). Compiled on server before execution on client. Interpreted (not compiled) by client. 9

10  JavaScript is written in the same way as HTML in a text editor (Notepad)  JavaScript implementation was quite similar to CSS; you can link to outside files (with the file extension.js), or write blocks of code into your HTML documents with the tag 10 How to Put a JavaScript Into an HTML Page

11 JavaScript can be put in the or in the of an HTML document JavaScript functions should be defined in the This ensures that the function is loaded before it is needed JavaScript in the will be executed as the page loads JavaScript can be put in a separate.js file Put this HTML wherever you would put the actual JavaScript code An external.js file lets you use the same JavaScript on multiple HTML pages The external.js file cannot itself contain a tag JavaScript can be put in HTML form object, such as a button This JavaScript will be executed when the form object is used Where Do You Place Scripts?

12 Scripts can either be in the section or section Convention is to place it in the section.... 12 Placement Scripts

13 Scripts can be provided locally or remotely accessible JavaScript file using src attribute Referencing External JavaScript File

14  Besides being an object oriented programming language, JavaScript is also an event-driven language. Let's take a look at what an event is.  Whenever the user does something on a Web page, whether it's loading the page, clicking on something, or moving the mouse over something, it's called an event.  For JavaScript to recognize an event, we need an event handler. Event handlers are easy to spot, as they usually start with the word "on". Two commonly used event handlers are: onclick and onmouseover.  In the case of onmouseover, it is attached to an object (let's say a link) on the page. As soon as the user puts the mouse pointer over the object that this particular event handler is attached to, then whatever you specify in the event handler will happen.  The JavaScript event handler is placed inside an HTML tag like so: Close this window 14 What is an Event?

15  onclick - Triggered when the object is clicked.  onmouseover - Triggered when the mouse moves over the object.  onmouseout - Triggered when the curser moves off of the object.  onblur - Triggered when the object is no longer selected (like a form object, or when a window is no longer in front.  onfocus - Triggered when an object is brought to focus, such as bringing a window in front of another.  onload - Triggered when the object is done loading.  onunload - Triggered when the user unloads the page. (Loads another page into the Window)  onsubmit - Triggered when the user submits a form.  onselect - Triggered when the user selects the contents of an object.  onchange - Triggered when the user changes an object. (such as making a different selection in a form)  onerror - Triggered when a JavaScript error is encountered.  onabort - Triggered when the user stops the page from loading.  http://www.w3schools.com/js/js_events_examples.asp 15 Commonly used event handlers

16 16 document.write("HelloWorld!") The above code will produce this output on the HTML page. HelloWorld!!

17 17  To insert a JavaScript into an HTML page, we use the tag.  The and tells where the JavaScript starts and ends  The script tag encloses any script code you want to use  The type attribute alert the browser to the type of script it is about to deal with, it helps in code interpretation.

18 18  The comments around the script are there so that old browsers that don’t understand the script tag won’t display the code as text on the page.  If the browser can do JavaScript, then it will ignore the comments.

19 19...

20 20  The word document.write is a standard JavaScript command for writing output to a page.  If we had not entered the tag, the browser would have treated the document.write("Hello World!") command as pure text, and just write the entire line on the page.  This will be the output document.write("Hello World!")

21 21  You can place an unlimited number of scripts in your document, so that you can have scripts in both the body and the head section. …… ……

22 22 External scripts  To import scripts from external JavaScript files, save the code in the text file with the.js extension; without the script tags and comment.

23 23 A simple example for external scripts  Save as main.html  Save as hello.js <script language="javascript" type="text/javascript" src="hello.js"> var hello = 'Hello World'; document.write(hello);

24 24 Output Hello World!

25 25 tag  The noscript element is used to define an alternate content (text) if a script is NOT executed.  This tag is used for browsers that recognizes the tag, but does not support the script in it.  If a browser supports scripting, it will not display the text in the noscript element.

26 26 Example Your browser does not support JavaScript!

27 27...... Your browser does not support JavaScript!......

28 JavaScript has three “primitive” types: number, string, and boolean Numbers are always stored as floating-point values Hexadecimal numbers begin with 0x Some platforms treat 0123 as octal, others treat it as decimal Strings may be enclosed in single quotes or double quotes Strings can contains \n (newline), \" (double quote), etc. Booleans are either true or false 0, "0", empty strings, undefined, null, and NaN are false, other values are true Primitive Datatypes

29 You create a variable with or without the “var” statement  var num = “1”;  var name = “Kaushal”;  var phone = “123-456-7890”; Variables names must begin with a letter or underscore Variable names are case-sensitive Variables are untyped (they can hold values of any type) The word var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page) JavaScript Variable

30 Comments are as in C or Java: Single Line Comment // Paragraph Comment /*….*/ Java’s javadoc comments, /**... */, are treated just the same as /*... */ comments ; they have no special meaning in JavaScript Comments

31 31

32 32

33 33

34 Alert box > User will have to click "OK" to proceed > alert("sometext") Confirm box > User will have to click either "OK" or "Cancel" to proceed > confirm("sometext") Prompt box > User will have to click either "OK" or "Cancel" to proceed after entering an input value > prompt("sometext","defaultvalue") 34 JavaScript Popup Boxes

35  Write a program by putting all of the alert statements into the section of the page. This way, they load up before that page even displays any data  Yourcode should have the following info:   Follow up the above code with another little script with another write() method to give you a message:  document.write('wasn\'t that annoying?'); 35 Practice

36  Scripts that will write out text or HTML code out onto the page must be placed in its section.  To write out text or HTML to a page, we use the document object's write() method.  JavaScript statements should always end with a semicolon (;).  Scripts placed inside HTML tags write out text the same as if they were not written out by JavaScript.  Alert boxes can be used to grab the viewer's attention.  When placing an event handler in an anchor, you can use href="#" as the link.  The return false; statement prevents the browser from acting on the link contained in the href attribute.  You can also use javascript:; as a link for an event handler, in which case you don't need the return false; statement.  Escaping a character using the backslash character (\) tells the browser to ignore the character that immediately follows it.  Alert() is a method of the window object 36 Your First Scripts Summary

37 JavaScript allows you to declare and use variables to store values. How to assign a name to a variable? – Include uppercase and lowercase letters – Digits from 0 through 9 – The underscore _ and the dollar sign $ – No space and punctuation characters – First character must be alphabetic letter or underscore – Case‐sensitive – No reserved words or keywords 37 Variables

38  Variables  Variables are very important for any kind of programming. Without them, complex scripts would never be possible. When used correctly, they can also save you a lot of typing. The ability to effectively use variables is what separates a good programmer from a sloppy one.  What is a Variable?  The best way to think of a variable is as a container. With a conventional container, you use it to put things in. Variables work in the same way. However, instead of putting things into them, we assign them values. So we could also say that variables contain values.  Defining Variables  When you first tell JavaScript about a variable, it is call declaring it. The best way to declare a variable is to use the word var before it.  A variable can be defined by assigning it a value. For example:  var my_number = 10; 38 Variables

39 39

40  You can also declare a variable without assigning it a value, like so:  var my_number;  It is usually a good programming practice to declare all of your variables at the beginning of the script. You don't necessarily need to assign any values to them, but this way they have been declared, or initialized. This is kind of like laying out all the tools you might need to work on your car before you start working. This also lets you see at a glance all of the variables you are dealing with in the script. 40 Variable Declarations

41  Here's an example: var first_name = "betty";  Now the variable first_name has the value of "betty". Whenever you will be re-using any kind of text, especially long bits of text, it can be useful to make it into a variable. For example:  document.write("This is some text that will be written out several times within the page");  Instead of having to do this again and again, you could assign the text (also called a text string) to a variable:  var my_text = "This is some text that will be written out several times within the page";  document.write(my_text);  Now this text string can be written out many times using only the variable my_text. This may seem a little pointless right now, but as you start writing larger and larger scripts, this will be a very good habit. 41 Variables can also have text values.

42 42

43  About the above example.  The text for the variable is enclosed in quotes. For JavaScript to assign text to a variable, it must be enclosed in quotes. These can be either single or double quotes.  When we refer to the variable my_text inside the write() method, we don't use the quotes. If we were to enclose my_text inside quotes, then the words "my_text" would be written out to the document. When referring to a variable, don't enclose it in quotes. 43 Observations

44  Sometimes it can seem a little confusing as to when you should use var, and when you don't need to. So let's clear this up a bit.  You don't need to use var for the same variable more than once, you only need it when you first declare that variable. For example, let's say you declare a variable without assigning it a value early in your script.  var my_name;  Later on in your script, you may want to assign my_name a value. Since you have already declared the variable at the beginning of your script, you don't need to use var again.  my_name = "mortimer";  Note: You may notice when looking at some scripts that people don't always use var when declaring variables. This will probably work much of the time, but to be on the safe side, I would recommend that you should always declare your variables with var. 44 To var or not to var

45  A variable can be thought of as a container that you put things into.  Variables are assigned values.  The first time you use a variable in a script, it is called declaring, or initializing it.  Variables can have text string, numeric, or boolean values.  Text string values must be enclosed in quotes.  The value of a variable can be changed at any time in the script.  It is a good idea to give your variables descriptive names.  Variable names cannot start with numbers, contain spaces or punctuation. They also cannot use words reserved by JavaScript.  JavaScript variable names are case sensitive.  When you first declare a variable, use the word var in front of it.  var only needs to be used once for a variable. 45 Variables Summary

46 JavaScript allows the same variable to contain different types of data values. Primitive data types – Number: integer & floating‐point numbers – Boolean: logical values “true” or “false” – String: a sequence of alphanumeric characters Composite data types (or Complex data types) – Object: a named collection of data – Array: a sequence of values Special data types – Null: an initial value is assigned – Undefined: the variable has been created but not yet assigned a value 46 Data Types

47 It is an important part of any programming language for doing arithmetic calculations. JavaScript supports: – Integers: A positive or negative number with no decimal places. Ranged from –253 to 253 – Floating‐point numbers: usually written in exponential notation. 3.1415…, 2.0e11 47 Numeric Data Types

48 A string variable can store a sequence of alphanumeric characters, spaces and special characters. String can also be enclosed in single quotation marks (‘) or in double quotation marks (“). What is the data type of “100”? – String but not number type Pay attention to the special characters. 48 Strings

49 49 Strings example

50 An object is a thing, anything, just as things in the real world. – E.g. (cars, dogs, money, books, …) In the web browser, objects are the browser window itself, forms, buttons, text boxes, … Methods are things that objects can do. – Cars can move, dogs can bark. – Window object can alert the user “alert()”. All objects have properties. – Cars have wheels, dogs have fur. – Browser has a name and version number. 50 What is an Object?

51  JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types.  We will only look at the built-in JavaScript objects, and how they are used. The next slides will explain each built-in JavaScript object in detail.  Remember that an object is just a special kind of data. An object has properties and methods. 51 Object in JavaScript

52 52 Object in JavaScript The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram. The window itself is an object that have document in it. In document it has another object such as images and forms. Each of these objects have its own properties and methods.

53 53 Object in JavaScript - properties Properties are the values associated with an object. Below examples shows how to access length property of document object to return the number of characters in a string. var txt="Hello World!“ document.write(txt.length) The output of the code above will be: 12 ( H e l l o [space] W o r l d ! )

54 54 Object in JavaScript - methods Methods are the actions that can be performed on objects. In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: var str="Hello world!" document.write(str.toUpperCase()) The output of the code above will be: HELLO WORLD!

55 ObjectPropertiesMethods WindowdefaultStatus, frames, opener, parent, scroll, self, status, top, window Alert, blur,close, confirm, focus, open, prompt, clearTimeout, setTimeout FramedefaultStatus, frames, opener, parent, scroll, self, status, top, window Alert, blur, close, confirm, focus, open, prompt, clearTimeout, setTimeout LocationHash, host, hostname, href, pathname, por, protocol, search Reload, replace HistoryLength, forward, goBack NavigatorappCodeName, appName, appVersion, mimeTypes, plugins, userAgents javaEnabled DocumentsalinkColor, anchors, applets, ares, bgColor, cookie, fgColor, forms, images, lastModified, linkColor, links, location, referrer, title, vlinkColor Clear, close, open, write, writeln ImageBorder, complete, heigth, hspace, lowwsrc, vspace, width None FormAction, elements, encoding, FileUpload, method, name, target Submit, reset TextdefaultValue, name, type, valueFocus, blur, select 55 The most commonly used JavaScript objects

56 ObjectsPropertiesMethods ArrayLengthJoin, reverse, sort xx DateNonegetDate, getDay, getHours, getMinutes, getMonth, getSeconds, getTime, getTimeZoneoffset, getYear, parse, prototype, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear, toGMTString, toLocaleString, UTC StringLength, PrototypeAnchor, big, blink, bold, charAt, fixed, fontColor, fontSize, indexOf, italics, lastIndexOf, link, small, split, strike, sub, substring, sup, toLowerCase,toUpperCase 56 The most commonly used Built-in JavaScript Objects

57  String Object  Date Object  Array Object  Math Object  Boolean Object 57 Built-in JavaScript Objects

58  The String object is used to manipulate a stored piece of text.  The following example uses the length property of the String object to find the length of a string: var txt="Hello World!” document.write(txt.length)  The above code will result in following output: 12 58 Built-in JavaScript Objects - String

59  The Date object is used to work with dates and times.  Example below shows how to use Date() method to get today’s date: document.write(Date())  The output will be: Mon June 09 15:51:51 2012 59 Built-in JavaScript Objects - Date

60  This 2 nd example shows how to use getTime() method to calculate years since 1970: var minutes = 1000*60 var hours = minutes*60 var days = hours*24 var years = days*365 var d = new Date() var t = d.getTime() var y = t/years document.write("It's been: " + y + " years since 1970/01/01!")  The output will be: It's been: 37.86941401639396 years since 1970/01/01! 60 Built-in JavaScript Objects - Date

61  The Array object is used to store a set of values in a single variable name. 1.We create a new Array by assigning it to a new keyword, myArray: var mycars=new Array() mycars[0]=“Lotus" mycars[1]="Volvo" mycars[2]="BMW" OR var mycars=new Array("Saab","Volvo","BMW") 61 Built-in JavaScript Objects - Array

62 2.We can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.  The following code line: document.write(mycars[0])  will result in the following output: Lotus 3.To modify a value in an existing array, just add a new value to the array with a specified index number and then try to access it: mycars[0]=“Lexus” document.write(mycars[0]) will result in the following output: Lexus 62 Built-in JavaScript Objects - Array

63  Functions are a great way to help you write more economical JavaScript code. Scripts that make good use of functions are capable of doing far more than scripts that don't. As you will see in this lecture, functions are a great thing to know how to use. 63 Functions

64 A function is a block of organized reusable code (a set of statements) for performing a single or related action. Begins with keyword “function” and the function name and “( …)” Inside the parentheses – We can pass parameters to the function – E.g. function myfuc(arg1, arg2) {…} – Built‐in and user‐defined functions 64 Functions

65 Functions provided by the language and you cannot change them to suit your needs. Some of the built‐in functions in JavaScript are shown here: – eval ‐ eval(expr) eval evaluates the expression or statements – isFinite Determines if a number is finite – isNaN Determines whether a value is “Not a Number” – parseInt Converts string literals to integers, no number NaN. – parseFloat Finds a floating‐point value at the beginning of a string. 65 Built ‐ In Functions

66  A function is basically like a bit of self contained code within a script. In form, it is rather similar to a conditional or even a loop in that all of its statements are contained inside curly braces.  A function can either carry out an action (or set of actions), return a value, or both. Good functions can be re-used over and over again. They can be thought of as building blocks that can be used in numerous other scripts.  Functions take the following form: function myFunction(parameters) { statements contained within the function; } 66 Functions

67 For some functionality, you cannot achieve by only using the built‐in functions. You can define a function as follows function (parameters) { // code segments; } 67 User ‐ Defined Functions

68  Here is an example of a script that checked for an @ symbol and returned either a -1 or its position in the string.  function checkEmail() {  var email_addy = prompt('Please enter your email address',''); var is_email = email_addy.indexOf('@'); alert(is_email);  }  Notice that the function contents are indented the same way that we indented conditionals and loops earlier. This is good coding practice as it makes your code easier to read and understand. 68 Example

69  A function will only run when it is asked to. This is referred to as calling a function. Functions are commonly called from within event handlers (remember those?), but functions can also be called from other areas of the script, including other functions. 69 Calling Functions

70  A function is called within a script by writing its name, followed by parentheses, with or without parameters. Let’s look at functions without parameters, for simplicity's sake.  alert('we need to check to see where the @ symbol is at');  //Call the function checkEmail();  If we are assuming this is a separate script from the one above (and we are), then we don't need to include the function itself in this script. It can be called from anywhere on the page. Once again, not only can a function be called from inside a script, it can also be called from inside another function. 70 Calling a Function From a Script

71  One of the more common ways to call a function is with an event handler. Such an event handler could look something like this: Click to see an image change  In this case, the event handler onclick will call the function swapImage().  A function can also be called without user interaction when the page loads by using the onload event handler:  71 Calling a Function With an Event Handler

72  You can pass variables to functions from other areas of the page. This is done using the function's parameters. Here's how this is done. Let's start with the event handler:  Click to pass some variables to a function  As you can see, we placed three text strings, separated by commas, between the parentheses of the function call. Here's the function:  function varPassTest(name1, name2, name3) { alert(name1 + name2 + name3); }  When you click on the link that contains the event handler, the three values are passed to the function.  The function itself has three parameters, name1, name2, and name3.  The only thing contained within the function itself is an alert box that will display all three variables. (Note: you don't need to initialize these variables with the var statement, as the are already automatically initialized when used this way. ) 72 Passing Variables

73  This function is a self contained simple function whose sole purpose is to add a dollar sign ($) to a number that you input. The script inside the of the document will ask you for the number and print out the result. The function is contained in the section.  Here is the body script: // Prompt the user for a number. var initial_number = prompt('Please type in a number',''); // Call the function, and pass it initial_number for processing. fixed_number = addDollar(initial_number); // take the number the function returned and write it out. document.write('This is your number converted to a dollar amount: ' + fixed_number); Here is the function in the script. function addDollar(num) { // add the dollar sign before the number, and.00 after. new_number = '$' + num + '.00'; // return the num variable back out of the function. return new_number; } 73 Simple function

74  Explanation about what happens in these scripts.  The user is prompted for a number, which is assigned to the initial_number variable.  initial_number gets passed to the function addDollar.  Once in the function, the value of initial_number is assigned to the function's parameter, num.  new_number is given the value of num with a dollar ($) character before it, and a period and two dots after.  The statement return new_number; returns the value of new_number back out of the function.  The returned variable is assigned to fixed_number.  fixed_number is printed out on the screen.  This function we just created can be used again and again in this document, and in turn re-used later on in other scripts and documents if you like. It is singular in its purpose, which is to turn any number passed to it into a dollar amount. 74 Explanation

75  The Math object allows you to perform common mathematical tasks.  The Math object includes several mathematical values and functions. You do not need to define the Math object before using it. 75 Built-in JavaScript Objects - Math

76  JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object.  These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.  You may reference these values from your JavaScript like this: Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E 76 Built-in JavaScript Objects – Math - values

77  In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available.  The following example uses the round() method of the Math object to round a number to the nearest integer: document.write(Math.round(4.7))  The code above will result in the following output: 5 77 Built-in JavaScript Objects – Math - methods

78  The Boolean object is an object wrapper for a Boolean value.  The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).  We define a Boolean object with the new keyword. The following code line defines a Boolean object called myBoolean: var myBoolean=new Boolean() 78 Built-in JavaScript Objects - Boolean

79  If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false").  Example of Boolean object with initial value of false: var myBoolean=new Boolean() var myBoolean=new Boolean(0) var myBoolean=new Boolean(null) var myBoolean=new Boolean("") var myBoolean=new Boolean(false) var myBoolean=new Boolean(NaN)  Example of Boolean object with initial value of true: var myBoolean=new Boolean(true) var myBoolean=new Boolean("true") var myBoolean=new Boolean("false") var myBoolean=new Boolean("Richard") 79 Built-in JavaScript Objects - Boolean

80  JavaScript deals with objects. One good way to think about this is to compare it to real life objects. Let's take a car for example. A car is an object. The car has wheels, and these wheels each have tires. If we were to write out these objects in dot syntax, it would look like this:  car.wheels.tires  Besides tires, car wheels also have hubcaps (ok, not all cars, but let's assume so). So these objects can be written out this way:  car.wheels.hubcaps  Going back to the tires, we can take this a step further. The car's tires have tread. So this can be written out in dot syntax like this:  car.wheels.tires.tread  Therefore, it would obviously be incorrect to write cars.wheels.hubcaps.tread, as hubcaps don't have tread, but tires do. Get it? Good. 80 Objects

81  These objects can also have properties. By changing the properties of an object, you change the object. For example, the color of the hubcaps on the car are gray. This can be written out as:  car.wheels.hubcaps.colour.grey  If we wanted to change the colour of our car's hubcaps, we could do so by writing:  car.wheels.hubcaps.colour.silver  Ok, we can't to that to a car (if only it were that easy), but we can do this in JavaScript. As we will see.  One other thing to note is that many of our car's properties (wheels, hubcaps, etc) are also objects in their own right, which can have their own properties. 81 OBJECTS

82 1.Create a direct instance of an object 2.Create template of an object 82 How to create an object?

83 83 Object A bird (object) Fly () name age EyeColor Eat() Drink() METHODSPROPERTIES

84 1. Direct Instance Add a few properties to the bird BirdObj=new Object() BirdObj.name=“MorningBird“ BirdObj.age=2 BirdObj.eyecolor=“green" Add methods to the bird BirdObj.fly = fly BirdObj.eat = eat BirfObj.Breath = breath 84

85 2. Create Template to the object function Bird(name,age,eyecolor) { this.name=name this.age=age this.eyecolor=eyecolor } When you have template, then you can create new instance of the object : myBird= new Bird (“Parrot”, 2, “blue”) 85

86  You can also add some methods to the bird object. This is also done inside the template: function Bird(name,age,eyecolor) { this.name=name this.age=age this.eyecolor=eyecolor this.habitat = habitat  new method } That methods are just functions attached to objects. Then we will have to write the habitat() function: function habitat(new_habitat) { this.habitat=new_habitat } Eg : myBird.habitat(“Pond”) 86

87  Cookies are variables that can be stored on a user's computer and be picked up by any other web pages in the correct domain and path. Cookies are set to expire after a certain length of time. They are limited to storing string values only.  Be warned that many users (including me) will not permit cookies on their computers. Do not make your web sites rely on them.  The reason for this is that many web sites only use cookies as part of advert tracing systems, which they use to track your movement around the Internet.  I would not want anyone to follow me around a city while I was shopping, taking notes of every shop I visit as that would be an invasion of my privacy. Many people feel the same applies to the Internet. You may find it helps to firstly display a message saying what you are going to use the cookie for, for example to store a username and password for the next time they visit the site. 87 Cookies

88  Some browsers will have a limit to how many cookies they can store, usually 300 cookies or more, of which there may be 20 cookies per domain name.  A total of 4 KB (after encoding) of cookies can be stored for any domain or path.  The document.cookie object is a string representation of all cookies available to the current web page.  Thedocument.cookie object is somewhat unusual in that when you assign string values to it, it does not become the value that you assign to it.  Instead, it takes a part of that value and appends its current value to that, so making a string containing several pairs of variableName=variableValue. 88 Cookies

89  Cookies are created or modified by assigning a name=value pair to the document.cookie object: document.cookie = cookieString;  The cookieString is more than just a single value. As well as a value, it can contain other information, such as when you want the cookie to expire, and what file paths it should apply to.  Any of these values that you want to specify should be put together in a string as keyword=value; keyword=value;etc. and assigned as a single string to document.cookie. Only the cookie name and value are required, all other values are optional. 89 Creating / modifying and deleting cookies

90  cookieName and cookieValue are strings, and must be URL encoded. They can contain any characters. To URL encode a cookie name or value, you can use the escape method.  Unfortunately, this cannot cope with unicode characters. Newer browsers will also provide the encodeURIComponent method that is able to cope with unicode, but if you use this, you will lose support for older browsers. This must be written in full.  The Date.toGMTString() method can return dates in the correct format for you. For example:var theDate = new Date(); var oneYearLater = new Date( theDate.getTime() + 31536000000 ); var expiryDate = oneYearLater.toGMTString();  Once the specified date is reached, the cookie expires and is deleted. If expires is not specified, the cookie will be deleted when the browser is closed. If expires is set to a date in the past, the cookie is deleted immediately.  This is how to delete a cookie (some browsers may take a few seconds to actually delete the cookie). 90 Cookies

91  The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents  All HTML elements, along with their containing text and attributes, can be accessed through the DOM.  The contents can be modified or deleted, and new elements can be created.  JavaScript uses the HTML Document Object Model to manipulate HTML.  Levels of the DOM are dot-separated in the syntax. 91 DOM: What is it?

92 DOM Specification: “a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents. … [DOM] provides a standard set of objects for representing HTML and XML documents, a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them.” 92 DOM: What is it?

93 Anchor object Document object Event object Form and Form Input object Frame, Frameset, and IFrame objects Image object Location object Navigator object Option and Select objects Screen object Table, TableHeader, TableRow, TableData objects Window object HTML DOM Objects

94 Java-based parsers (e.g. Sun Project X, IBM XML4J, Apache Xerces) MS IE5 browser: COM programming interfaces for C/C++ and MS Visual Basic, ActiveX object programming interfaces for script languages 94 DOM: Implementations

95 Object model covers structure of a document behaviour of a document and its constituent objects DOM defines interfaces and objects for representing and manipulating documents semantics of these interfaces relationships between interfaces and objects 95 Object-based document modelling

96 Based on O-O concepts: methods (to access or change object’s state) interfaces (declaration of a set of methods) objects (encapsulation of data and methods) Roughly similar to the XSLT/XPath data model  a parse tree 96 DOM structure model

97 97 invoice invoicepage name addressee addressdata address form="00"type="estimatedbill" Leila Laskuprintti streetaddresspostoffice 70460 KUOPIO Pyynpolku 1 <invoice> <invoicepage form="00" <invoicepage form="00" type="estimatedbill"> type="estimatedbill"> Leila Laskuprintti Leila Laskuprintti Pyynpolku 1 Pyynpolku 1 70460 KUOPIO 70460 KUOPIO......Document Element NamedNodeMap Text XML DOM structure model

98 98 HTML DOM structure model The DOM presents an HTML document as a tree-structure (a node tree), with elements, attributes, and text.

99 The application support and intermediate DOM which existed before the creation of DOM Level 1. Example include the DHTML object model or the Netscape intermediate DOM. Level 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process. 99 Structure of DOM Level 0

100 Two parts: I: DOM Core Interfaces Fundamental interfaces low-level interfaces to structured documents Extended interfaces (next page) XML specific: CDATASection, DocumentType, Notation, Entity, EntityReference, ProcessingInstruction II: DOM HTML Interfaces  more convenient to access HTML documents Level 1 intentionally limited to representation and manipulation of document structure and content document instance only; no access to the contents of a DTD 100 Structure of DOM Level 1

101 support for namespaces accessing elements by ID attribute values optional features interfaces to document views and stylesheets an event model (for, say, user actions on elements) methods for traversing the document tree and manipulating regions of document (e.g., selected by the user of an editor) 101 DOM Level 2

102 Consists of 6 different specifications: 1.DOM Level 3 Core; 2.DOM Level 3 Load and Save 3.DOM Level 3 XPath; 4.DOM Level 3 Views and Formatting; 5.DOM Level 3 Requirements; and 6.DOM Level 3 Validation, which further enhances the DOM 102 DOM Level 3

103 103 Core Interfaces: Node & its variants Node Comment DocumentFragmentAttr Text Element CDATASection ProcessingInstruction CharacterData EntityDocumentTypeNotation EntityReference “Extendedinterfaces” Document

104 104 DOM interfaces: Node invoice invoicepage name addressee addressdata address form="00" type="estimatedbill" Leila Laskuprintti streetaddresspostoffice 70460 KUOPIOPyynpolku 1NodegetNodeTypegetNodeValuegetOwnerDocumentgetParentNode hasChildNodesgetChildNodes getFirstChildgetLastChildgetPreviousSiblinggetNextSibling hasAttributesgetAttributes appendChild(newChild)insertBefore(newChild,refChild)replaceChild(newChild,oldChild)removeChild(oldChild)Document Element NamedNodeMap Text

105 105 invoice invoicepage name addressee addressdata address form="00"type="estimatedbill" Leila Laskuprintti streetaddresspostoffice 70460 KUOPIO Pyynpolku 1 DocumentgetDocumentElementcreateAttribute(name)createElement(tagName)createTextNode(data)getDocType()getElementById(IdVal) Node Document Element NamedNodeMap Text DOM interfaces: Document

106 106 DOM interfaces: Element invoice invoicepage name addressee addressdata address form="00"type="estimatedbill" Leila Laskuprintti streetaddresspostoffice 70460 KUOPIO Pyynpolku 1 ElementgetTagNamegetAttributeNode(name)setAttributeNode(attr)removeAttribute(name)getElementsByTagName(name)hasAttribute(name) Node Document Element NamedNodeMap Text

107 to handle ordered lists of nodes: NodeList e.g. from Node.childNodes or Element.getElementsByTagName("name") all descendant elements of type "name" in document order to access unordered sets of nodes by name: NamedNodeMap e.g. from Node.attributes NodeList s and NamedNodeMap s are "live": changes to the document structure reflected to their contents 107 Additional Core Interfaces

108 Each DOM object X lives in the context of a Document: X.ownerDocument Objects implementing interface Y are created by factory methods D.create Y (…), where D is a Document object. E.g: createElement("A"), createAttribute("href"), createTextNode("Hello!") Creation and persistent saving of Document s left to be specified by implementations 108 Object Creation in DOM

109 public static void main(String args[]){ if (args.length > 0) { String fileName = args[0]; BuildXml buildXml = new BuildXml(fileName); } else { System.err.println( "Give filename as argument"); }; } // main 109 The main routine for BuildXml

110 110 HTML Node Hierarchy

111 How Javascript Interact With HTML DOM 111 The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are: A) Opening or popping up a new window with programmatic control over the size, position and 'look' of the new window (i.e. whether the menus, toolbars, etc. are visible). B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server. C) Changing images as the mouse cursor moves over them: This effect is often used to draw the user's attention to important links displayed as graphical elements.

112 Javascript Objects ObjectDescription WindowRepresents a browser window. A that is created automatically with every instance of a or tag NavigatorContains information about the client's browser ScreenContains information about the client's display screen LocationContains information about the current URL HistoryContains the visited URLs in the browser window 112

113 HTML DOM Objects ObjectDescription AnchorRepresents an element DocumentRepresents the entire HTML document and can be used to access all elements in a page. Frame / frameset Represents a / element ImageRepresents an element EventRepresents the state of an event FormRepresents a element Option / Select Represent an element / selection list in an HTML document. Table, TableHeader, TableRow Represent a, and element. 113

114  var link = document.createElement('a'); link.setAttribute('href', 'mypage.htm'); 114 Adding in a new element

115  by location:  document.childNodes[1].childNodes[0]  Find the main document element (HTML), and find its second child (BODY), then look for its first child (DIV)  by ID:  document.getElementById('myDiv').append Child(txt); 115 locating a slot in the document

116  document.childNodes[1].childNodes[1].childNodes[ 0].style.display = "none"; 116 Hiding an element

117  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM") xmlDoc.async="false" xmlDoc.load("note.xml") //....... processing the document goes here 117 Loading an XML document object into the parser

118  // load up variable var with some xml var text=" " text=text+" John Robert " text=text+" Reminder " text=text+" Don't forget your homework! " text=text+" " // now create the DO var xmlDoc = new ActiveXObject("Microsoft.XMLDOM") xmlDoc.async="false" xmlDoc.loadXML(text) //....... process the document 118 Manually loading XML into the parser

119  document.write(xmlDoc.parseError.property)  errorCode : Returns a long integer error code  reason : Returns a string explaining the reason for the error  line : Returns a long integer representing the line number for the error  linePos : Returns a long integer representing the line position for the error  srcText : Returns a string containing the line that caused the error  url : Returns the url pointing the loaded document  filePos : Returns a long integer file position of the error 119 parseError object

120 set xmlDoc=CreateObject("Microsoft.XMLDOM") xmlDoc.async="false" xmlDoc.load("note.xml") for each x in xmlDoc.documentElement.childNodes document.write(x.nodename) document.write(": ") document.write(x.text) next 120 Traversing nodes

121 var xmlDoc = new ActiveXObject("Microsoft.XMLDOM") xmlDoc.async="false" xmlDoc.load("note.xml") document.write(xmlDoc.getElementsByTagName("from").item (0).text) 121 Calling XML nodes by name

122 Questions


Download ppt "Web Programming Introduction to JavaScript 1. The growth of the WWW has resulted in a demand for dynamic and interactive websites. There are many different."

Similar presentations


Ads by Google