Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Advertisements

JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
Svetlin Nakov Telerik Corporation
The Web Warrior Guide to Web Design Technologies
Svetlin Nakov Telerik Corporation
JavaScript (Part 2) CS 183 4/13/2010. JavaScript (Part 2) Will cover: ◦ For.. In ◦ Events ◦ Try.. Catch, Throw ◦ Objects.
20-Jun-15 JavaScript and HTML Simple Event Handling.
Web Development & Design Foundations with XHTML Chapter 14 Key Concepts.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
CST JavaScript Validating Form Data with JavaScript.
Web Programming Material From Greenlaw/Hepp, In-line/On-line: Fundamentals of the Internet and the World Wide Web 1 Introduction The JavaScript Programming.
4.1 JavaScript Introduction
HTML Forms/Events (Instructor Lesson) The Event model HTML Forms Custom Events 1.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Event and Event Handling.
W. W. Milner JavaScript. W. W. Milner Chapter 1 - Intro Why use JavaScript? Interactivity LiveScript JavaScript Jscript ECMAScript JavaScript is not Java!
Scripting Languages.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
What is a dynamic web site and how to create it? Svetlin Nakov Telerik School Academy schoolacademy.telerik.com Technical Trainer
Bridges To Computing General Information: This document was created for use in the "Bridges to Computing" project of Brooklyn College. You are invited.
Past, Present and Future Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JavaScript Part 1.
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
DOM and JavaScript Aryo Pinandito.
DHTML: Dynamic HTML Internet Technology1. What is DHTML? A collection of enhancements to HTML ► To create dynamic and interactive websites Combination.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
JavaScript Development Introduction First Steps in JavaScript SoftUni Team Technical Trainers Software University
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
JavaScript. Overview Introduction: JavaScript basics Expressions and types Expressions and types Arrays Arrays Objects and Associative Arrays Objects.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Client-Side Scripting JavaScript.  produced by Netscape for use within HTML Web pages.  built into all the major modern browsers. properties  lightweight,
JavaScript - A Web Script Language Fred Durao
JavaScript Development Introduction First Steps in JavaScript Svetlin Nakov Technical Trainer Software University
JavaScript, jQuery, and Mashups Incorporating JavaScript, jQuery, and other Mashups into existing pages.
1 JavaScript
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Scott Marino MSMIS Summer Session Web Site Design and Authoring Session 8 Scott Marino.
All in one place Telerik School Academy HTML, CSS and JavaScript.
Svetlin Nakov Telerik Corporation
Jaana Holvikivi 1 Introduction to Javascript Jaana Holvikivi Metropolia.
Making dynamic pages with javascript Lecture 1. Java script java versus javascript Javascript is a scripting language that will allow you to add real.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
Web Programming Java Script & jQuery Web Programming.
CIS 3.5 Lecture 2.3 "Introduction to JavaScript".
Copyright © Terry Felke-Morris WEB DEVELOPMENT & DESIGN FOUNDATIONS WITH HTML5 7 TH EDITION Chapter 14 Key Concepts 1 Copyright © Terry Felke-Morris.
7. JavaScript Events. 2 Motto: Do you think I can listen all day to such stuff? –Lewis Carroll.
LESSON : EVENTS AND FORM VALIDATION -JAVASCRIPT. EVENTS CLICK.
Introduction to JavaScript
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
The Magic of Dynamic Web Pages Doncho Minkov Telerik Software Academy academy.telerik.com Technical Trainer
The Magic of Dynamic Web Pages Telerik Software Academy JavaScript Fundamentals.
COM621: Advanced Interactive Web Development Lecture 6 – JavaScript (cont.)
LECTURE 6 (ETCS-308) Subject teacher : Ms. Gunjan Beniwal
>> Introduction to JavaScript
JavaScript and HTML Simple Event Handling 11-May-18.
Web Development & Design Foundations with HTML5
Web Development & Design Foundations with HTML5 7th Edition
Introduction to JavaScript Development
14 A Brief Look at JavaScript and jQuery.
DHTML Javascript Internet Technology.
DHTML Javascript Internet Technology.
Web Programming and Design
Presentation transcript:

Svetlin Nakov Telerik Corporation

1. DHTML Technologies  XHTML, CSS, JavaScript, DOM 2. Introduction to JavaScript  What is JavaScript  Using JavaScript into Web Pages  In the Part  In an External.js File 2

 JavaScript Syntax  JavaScript Operators  JavaScript Data Types  JavaScript Pop-up Boxes  alert, confirm and prompt  Conditional and Switch Statements  Loops  Functions 3

 JavaScript OOP  Constructors  Properties  Functions  Inheritance  Polymorphism  Extending Prebuilt JavaScript Objects  Document Object Model  Debugging in JavaScript 4

Dynamic Behavior at the Client Side

 Dynamic HTML (DHTML)  Makes possible a Web page to react and change in response to the user’s actions  DHTML = HTML + CSS + JavaScript 6DHTML XHTMLCSSJavaScriptDOM

 HTML defines Web sites content through semantic tags (headings, paragraphs, lists, …)  CSS defines 'rules' or 'styles' for presenting every aspect of an HTML document  Font (family, size, color, weight, etc.)  Background (color, image, position, repeat)  Position and layout (of any object on the page)  JavaScript defines dynamic behavior  Programming logic for interaction with the user, to handle events, change page content, … 7

Dynamic Behavior in a Web Page

 JavaScript is a front-end scripting language developed by Netscape for dynamic content  Lightweight, but with limited capabilities  Can be used as object-oriented language  Client-side technology  Embedded in your HTML page  Interpreted by the Web browser  Simple and flexible  Powerful to manipulate the DOM 9

 JavaScript allows interactivity such as:  Implementing form validation  React to user actions, e.g. handle keys  Changing an image when moving mouse over it  Sections of a page appearing and disappearing  Content loading and changing dynamically  Performing complex calculations  Custom HTML controls, e.g. scrollable table  Implementing AJAX functionality 10

 Can handle events (e.g. onClick, onKeyDown )  Can read and write HTML elements and modify the DOM tree  Can validate form data  Can access / modify browser cookies  Can detect the user’s browser and OS  Can be used as object-oriented language  Can handle exceptions  Can perform asynchronous server calls (AJAX) 11

first-script.html 12 <html><body> alert('Hello JavaScript!'); alert('Hello JavaScript!'); </body></html>

small-example.html 13 <html><body> document.write('JavaScript rulez!'); document.write('JavaScript rulez!'); </body></html>

 The JavaScript code can be placed in:  tag in the head  tag in the body – not recommended  External files, linked via tag the head  Files usually have.js extension  External.js files are highly recommended  The.js files get cached by the Web browser 14 </script>

 JavaScript code is executed during the page loading or when the browser fires an event  All statements are executed at page loading  Some statements just define functions that can be called later  Function calls or code can be attached as "event handlers" via tag attributes  Executed when the event is fired by the browser 15

<html><head> function test (message) { function test (message) { alert(message); alert(message); }</script></head><body> <img src="logo.gif" <img src="logo.gif" onclick="test('clicked!')" /> onclick="test('clicked!')" /></body></html> image-onclick.html 16

 Using external script files:  External JavaScript file: 17 <html><head> </head><body> <button onclick="sample()" value="Call JavaScript <button onclick="sample()" value="Call JavaScript function from sample.js" /> function from sample.js" /></body></html> function sample() { alert('Hello from sample.js!') alert('Hello from sample.js!')} external-JavaScript.html sample.js The tag is always empty.

 The JavaScript syntax is similar to C# and Java  Operators ( +, *, =, !=, &&, ++, …)  Variables (typeless; declaration not obligatory)  Conditional statements ( if, else )  Loops ( for, while )  Arrays ( my_array[] ) and associative arrays ( my_array['abc'] )  Functions (can return value)  Function variables (like the C# delegates) 19

 JavaScript data types:  Numbers (integer, floating-point)  Boolean (true / false)  String type – string of characters in "" or ''  Arrays  Associative arrays (hash tables) 20 var myName = "You can use both single or double quotes for strings"; var my_array = [1, 5.3, "aaa"]; var my_hash = {a:2, b:3, c:"text"}; var i = 42; var b = true;

 Every variable can be considered as object  For example strings and arrays have member functions: 21 var test = "some string"; alert(test[7]); // shows letter 'r' alert(test.charAt(5)); // shows letter 's' alert("test".charAt(1)); //shows letter 'e' alert("test".substring(1,3)); //shows 'es' var arr = [1,3,4]; alert (arr.length); // shows 3 arr.push(7); // appends 7 to end of array alert (arr[3]); // shows 7 objects.html

 The + operator joins strings  What is "9" + 9?  Converting a string to number: 22 string1 = "fat "; string2 = "cats"; alert(string1 + string2); // fat cats alert("9" + 9); // 99 alert(parseInt("9") + 9); // 18 alert("alabala".indexOf('b')); // 3

23 var name = "Svetlin Nakov"; document.write(name.length); // 13 document.write(name[0]); // S document.write(name.charAt(1)); // v document.write(name.substring(0,1)); // S document.write(name.slice(8)); // Nakov document.write(name.split(' ')[1]); // Nakov document.write(name.indexOf(' ')); // 7 document.write(name.match(/N\w+/)); // Nakov document.write(name.match(/\d+/)); // null document.write( name.replace('N', 'T')); // Svetlin Takov name.replace('N', 'T')); // Svetlin Takov document.write(name.toLowerCase()); // svetlin nakov document.write(name.fontsize(20).bold()); // Svetlin Nakov // Svetlin Nakov strings.html

 Declaring a new empty array:  Declaring an array holding few elements:  Appending an element / getting the last element:  Reading the number of elements (array length):  Finding element's index in the array: 24 var arr = new Array(); var arr = [1, 2, 3, 4, 5]; arr.push(3); var element = arr.pop(); arr.length; arr.indexOf(1);

25 var arr = []; // arr is empty array arr.push(1); // arr = [1] arr.push([2, 3, 4]); // arr = [1, [2, 3, 4]] document.write(arr); // 1,2,3,4 arr.reverse(); // arr = [[2, 3, 4], 1] document.write(arr); // 2,3,4,1 arr[10] = 5; // arr = [[2, 3, 4], 1,,,,,,,, 5] document.write(arr); // 2,3,4,1,,,,,,,,,5 document.write(arr[8]); // undefined arr.sort(); // arr = [1, [2, 3, 4], 5,,,,,,,,] document.write(arr); // 1,2,3,4,5,,,,,,,, arr = arr.slice(0,2); // arr = [1,[2,3,4],5,,,,,] document.write(arr); // 1,2,3,4 arr = arr.splice(1,1); // arr = [[2, 3, 4]] document.write(arr); // 2,3,4 arrays.html

 Associative arrays keep name-value pairs  Just like the hash tables in C#  Creating an associative array and assigning key-value pairs:  Accessing value by key: 26 var ages = new Array(); ages["Peter"] = 21; ages["Lora"] = 19; document.write(ages["Peter"]); // 21 document.write(ages["Maria"]); // undefined

 Creating an associative array by specifying its key-value pairs:  Merging arrays: 27 var grades = { 'Kiril' : 5, 'Milena' : 6, 'Todor' : 6, 'Lora' : 5, 'Misho' : 4} 'Todor' : 6, 'Lora' : 5, 'Misho' : 4} document.write(grades["Lora"]); // 5 var merged = []; for (var key in firstArray) merged[key] = firstArray[key]; merged[key] = firstArray[key]; for (var key in secondArray) merged[key] = secondArray[key]; merged[key] = secondArray[key]; associative-arrays.html

 Alert box with text and [OK] button  Just a message shown in a dialog box:  Confirmation box  Contains text, [OK] button and [Cancel] button:  Prompt box  Contains text, input field with default value: 28 alert("Some text here"); confirm("Are you sure?"); prompt ("enter amount", 10);

sum-of-numbers.html 29 <html><head> JavaScript Demo JavaScript Demo function calcSum() { function calcSum() { value1 = value1 = parseInt(document.mainForm.textBox1.value); parseInt(document.mainForm.textBox1.value); value2 = value2 = parseInt(document.mainForm.textBox2.value); parseInt(document.mainForm.textBox2.value); sum = value1 + value2; sum = value1 + value2; document.mainForm.textBoxSum.value = sum; document.mainForm.textBoxSum.value = sum; } </head>

sum-of-numbers.html (cont.) 30 <body> <input type="button" value="Process" <input type="button" value="Process" onclick="javascript: calcSum()" /> onclick="javascript: calcSum()" /> <input type="text" name="textBoxSum" <input type="text" name="textBoxSum" readonly="readonly"/> readonly="readonly"/> </body></html>

prompt.html 31 price = prompt("Enter the price", "10.00"); alert('Price + VAT = ' + price * 1.2);

Greater than <= SymbolMeaning > < Less than >= Greater than or equal to Less than or equal to ==Equal != Not equal 32 unitPrice = 1.30; if (quantity > 100) { unitPrice = 1.20; unitPrice = 1.20;}

 The condition may be of Boolean or integer type: 33 var a = 0; var b = true; if (typeof(a)=="undefined" || typeof(b)=="undefined") { document.write("Variable a or b is undefined."); document.write("Variable a or b is undefined.");} else if (!a && b) { document.write("a==0; b==true;"); document.write("a==0; b==true;"); } else { document.write("a==" + a + "; b==" + b + ";"); document.write("a==" + a + "; b==" + b + ";");} conditional-statements.html

 The switch statement works like in C#: 34 switch (variable) { case 1: case 1: // do something // do something break; break; case 'a': case 'a': // do something else // do something else break; break; case 3.14: case 3.14: // another code // another code break; break; default: default: // something completely different // something completely different} switch-statements.html

 Like in C#  for loop  while loop  do … while loop 35 var counter; for (counter=0; counter<4; counter++) { alert(counter); alert(counter);} while (counter < 5) { alert(++counter); alert(++counter);} loops.html

 Functions structure the code  Splitting code into parts  Promote code reuse  Can take parameters  Can return a result 36 function average(a, b, c) { var total; var total; total = a+b+c; total = a+b+c; return total/3; return total/3;} Parameters come in here. Declaring variables is optional. Type is never declared. Value returned here.

 Functions are not required to return a value  When calling function it is not obligatory to specify all of its arguments  The function has access to all the arguments passed via arguments array 37 function sum() { var sum = 0; var sum = 0; for (var i = 0; i < arguments.length; i++) for (var i = 0; i < arguments.length; i++) sum += parseInt(arguments[i]); sum += parseInt(arguments[i]); return sum; return sum;} alert(sum(1, 2, 4)); functions-demo.html

 In JavaScript variables could hold a function reference (support for higher-order functions)  Just like the C# delegates 38 function aggregate(arr, start, func) { var result = start; var result = start; for (var item in arr) for (var item in arr) result = func(result, item); result = func(result, item); return result; return result;} var sum = function(arr) { return aggregate(arr, 0, return aggregate(arr, 0, function(a, b) { return a + b; } ); function(a, b) { return a + b; } );} alert(sum([1, 2, 3])); higher-order-functions.html

Properties, Functions, Inheritance 39

 The current design of the JavaScript language, did not fully implement the object-oriented paradigms  There are various implementations of object- oriented programming techniques being used on the Web today  Primary goals of OOP  Encapsulation  Polymorphism  Inheritance

 The simplest way is to used the built-in Object data type  In JavaScript, objects are implemented as a collection of named properties (key-value pairs)  JavaScript allows the creation of any number of properties in an object at any time  They are dynamic – do not have to be pre-defined in an object declaration or constructor 41 var student = new Object; obj.name = "Doncho Minkov"; obj.grade = 3;

 A new JavaScript class is defined by creating a function (serving as constructor)  When used with the new operator, a function serves as a constructor for that class  Internally, JavaScript creates an Object, and then calls the constructor function 42 function Student() { this.name = "Doncho Minkov"; this.name = "Doncho Minkov"; this.grade = 3; this.grade = 3;} var student = new Student;

 When defining a constructor function, we can make as many objects with the same properties as we want 43 function Student(name, grade) { this.name = name; this.name = name; this.grade = grade; this.grade = grade;} var doncho = new Student("Doncho Minkov", 3); var pesho = new Student("Pesho Peshov",2 ); var stamat = new Student("Stamat Geshov",4);

 We can add a functions (methods) to the class at any time 44 function Student(name, grade) { this.name = name; this.name = name; this.grade = grade; this.grade = grade; this.sayHello = function() { alert("Hi! I am " + this.name); this.sayHello = function() { alert("Hi! I am " + this.name); }} var doncho = new Student("Doncho Minkov", 3); doncho.sayHello(); defining-classes.html

45

 We can use the prototype object to add custom properties / methods to classes  That is reflected on all instances of the class  How to use the prototype object?  Simply reference the keyword prototype on the object before adding the custom property 46 function Circle() { } Circle.prototype.pi = ;

 Adding a function to a class at runtime using the prototype object 47 function Circle() { } Circle.prototype.pi = ; Circle.prototype.radius = 5; Circle.prototype.calculateArea = function () { return this.pi * this.radius * 2; return this.pi * this.radius * 2;} var circle = new Circle(); var area = circle.calculateArea(); alert(area); // prototype-object.html

 Dynamically add a function to a built-in class at runtime using the prototype object: 48 Array.prototype.showMax = function () { function () { var max = this[0]; var max = this[0]; for (var i = 1; i < this.length; i++) { for (var i = 1; i < this.length; i++) { if (max < this[i]) { if (max < this[i]) { max = this[i]; max = this[i]; } } return max; return max; } var array = new Array(9, 1, 11, 3, 4); var max = array.showMax(); alert(max); // 11 Attaching a method to the Array class

 To inherit a class in JavaScript you should set the prototype object of the subclass to the superclass class: 50 function Person(name) { this.name = name; this.name = name; this.talk = function () { this.talk = function () { alert("Hi! I am " + this.name); alert("Hi! I am " + this.name); }} function Student(name, grade) { this.name = name; this.name = name; this.grade = grade; this.grade = grade;} Student.prototype = new Person(); This way we say that the Student class will have all the functionality of the Person class inheritance.html

 Polymorphism = ability to take more than one form (objects have more than one type)  A class can be used through its parent interface  A child class may override some of the behavior of the parent class 51 Student.prototype = new Person(); Teacher.prototype = new Person(); var array = new Array( new Teacher("Gana","Math"), new Student("Gosho",3), new Teacher("Gana","Math"), new Student("Gosho",3), new Person("Pesho"), new Teacher("Mara","Literature")); new Person("Pesho"), new Teacher("Mara","Literature")); for (var i = 0; i < array.length; i++) { array[i].talk(); array[i].talk();} polymorphism.html

 Every HTML element is accessible via the JavaScript DOM API  Most DOM objects can be manipulated by the programmer  The event model lets a document to react when the user does something on the page  Advantages  Create interactive pages  Updates the objects of a page without reloading it 53

 Access elements via their ID attribute  Via the name attribute  Via tag name  Returns array of descendant elements of the element " el " 54 var elem = document.getElementById("some_id") var arr = document.getElementsByName("some_name") var imgTags = el.getElementsByTagName("img")

 Once we access an element, we can read and write its attributes 55 function change(state) { var lampImg = document.getElementById("lamp"); var lampImg = document.getElementById("lamp"); lampImg.src = "lamp_" + state + ".png"; lampImg.src = "lamp_" + state + ".png"; var statusDiv = var statusDiv = document.getElementById("statusDiv"); document.getElementById("statusDiv"); statusDiv.innerHTML = "The lamp is " + state"; statusDiv.innerHTML = "The lamp is " + state";}… <img src="test_on.gif" onmouseover="change('off')" onmouseout="change('on')" /> onmouseout="change('on')" /> DOM-manipulation.html

 Most of the properties are derived from the HTML attributes of the tag  E.g. id, name, href, alt, title, src, etc…  style property – allows modifying the CSS styles of the element  Corresponds to the inline style of the element  Not the properties derived from embedded or external CSS rules  Example: style.width, style.marginTop, style.backgroundImage 56

 className – the class attribute of the tag  innerHTML – holds all the entire HTML code inside the element  Read-only properties with information for the current element and its state  tagName, offsetWidth, offsetHeight, scrollHeight, scrollTop, nodeType, etc… 57

 We can access elements in the DOM through some tree manipulation properties:  element.childNodes  element.parentNode  element.nextSibling  element.previousSibling  element.firstChild  element.lastChild 58

 Warning: may not return what you expected due to differences between the Web browsers 59 var el = document.getElementById('div_tag'); alert (el.childNodes[0].value); alert (el.childNodes[1]. getElementsByTagName('span').id); getElementsByTagName('span').id);… test span test span </div> accessing-elements-demo.html

 JavaScript can register event handlers  Events are fired by the Browser and are sent to the specified JavaScript event handler function  Can be set with HTML attributes:  Can be accessed through the DOM: 61 var img = document.getElementById("myImage"); img.onclick = imageClicked;

 All event handlers receive one parameter  It brings information about the event  Contains the type of the event (mouse click, key press, etc.)  Data about the location where the event has been fired (e.g. mouse coordinates)  Holds a reference to the event sender  E.g. the button that was clicked 62

 Holds information about the state of [Alt], [Ctrl] and [Shift] keys  Some browsers do not send this object, but place it in the document.event  Some of the names of the event’s object properties are browser-specific 63

 Mouse events:  onclick, onmousedown, onmouseup  onmouseover, onmouseout, onmousemove  Key events:  onkeypress, onkeydown, onkeyup  Only for input fields  Interface events:  onblur, onfocus  onscroll 64

 Form events  onchange – for input fields  onsubmit  Allows you to cancel a form submission  Useful for form validation  Miscellaneous events  onload, onunload  Allowed only for the element  Fires when all content on the page was loaded / unloaded 65

 onload event 66 <html><head> function greet() { function greet() { alert("Loaded."); alert("Loaded."); } </head> </body></html> onload.html

 The browser provides some read-only data via:  window  The top node of the DOM tree  Represents the browser's window  document  holds information the current loaded document  screen  Holds the user’s display properties  browser  Holds information about the browser 68

69 window navigatorscreendocumenthistorylocation form buttonselect form

 window.open() 70 var newWindow = window.open("", "sampleWindow", "width=300, height=100, menubar=yes, "width=300, height=100, menubar=yes, status=yes, resizable=yes"); status=yes, resizable=yes");newWindow.document.write( " " Sample Title Sample Title Sample Sample Text "); Text "); newWindow.status = "Hello folks"; "Hello folks"; window-open.html

71 alert(window.navigator.userAgent); The navigator in the browser window The userAgent (browser ID) The browser window

 The screen object contains information about the display 72 window.moveTo(0, 0); x = screen.availWidth; y = screen.availHeight; window.resizeTo(x, y);

 document object  Provides some built-in arrays of specific objects on the currently loaded Web page  document.location  Used to access the currently open URL or redirect the browser 73 document.links[0].href = "yahoo.com"; document.write( "This is some bold text "); "This is some bold text "); document.location = "

74 function checkForm() { var valid = true; var valid = true; if (document.mainForm.firstName.value == "") { if (document.mainForm.firstName.value == "") { alert("Please type in your first name!"); alert("Please type in your first name!"); document.getElementById("firstNameError"). document.getElementById("firstNameError"). style.display = "inline"; style.display = "inline"; valid = false; valid = false; } return valid; return valid;}… … form-validation.html

 The Math object provides some mathematical functions 75 for (i=1; i<=20; i++) { var x = Math.random(); var x = Math.random(); x = 10*x + 1; x = 10*x + 1; x = Math.floor(x); x = Math.floor(x); document.write( document.write( "Random number (" + "Random number (" + i + ") in range " + i + ") in range " + " > " + x + " > " + x + " "); " ");} math.html

 The Date object provides date / calendar functions 76 var now = new Date(); var result = "It is now " + now; document.getElementById("timeField").innerText = result;.innerText = result;... dates.html

 Make something happen (once) after a fixed delay 77 var timer = setTimeout('bang()', 5000); clearTimeout(timer); 5 seconds after this statement executes, this function is called Cancels the timer

 Make something happen repeatedly at fixed intervals 78 var timer = setInterval('clock()', 1000); clearInterval(timer); This function is called continuously per 1 second. Stop the timer.

79 function timerFunc() { function timerFunc() { var now = new Date(); var now = new Date(); var hour = now.getHours(); var hour = now.getHours(); var min = now.getMinutes(); var min = now.getMinutes(); var sec = now.getSeconds(); var sec = now.getSeconds(); document.getElementById("clock").value = document.getElementById("clock").value = "" + hour + ":" + min + ":" + sec; "" + hour + ":" + min + ":" + sec; } setInterval('timerFunc()', 1000); setInterval('timerFunc()', 1000);</script> timer-demo.html

 Modern browsers have JavaScript console where errors in scripts are reported  Errors may differ across browsers  Several tools to debug JavaScript  Microsoft Script Editor  Add-on for Internet Explorer  Supports breakpoints, watches  JavaScript statement debugger ; opens the script editor 81

 Firebug – Firefox add-on for debugging JavaScript, CSS, HTML  Supports breakpoints, watches, JavaScript console editor  Very useful for CSS and HTML too  You can edit all the document real-time: CSS, HTML, etc  Shows how CSS rules apply to element  Shows Ajax requests and responses  Firebug is written mostly in JavaScript 82

83

 The console object exists only if there is a debugging tool that supports it  Used to write log messages at runtime  Methods of the console object:  debug(message)  info(message)  log(message)  warn(message)  error(message) 84

Questions?