1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Introducing JavaScript
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Java Script Session1 INTRODUCTION.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
EIW: Javascript the Language1 The JavaScript Language.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
1 Representation and Management of Data on the Web Client Side Programming.
1 Browser Scripting JavaScript. 2 Introduction 3 Client-Server Architecture In a client-server architecture, computation is done either in the client.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
1 JavaScript. 2 Browser Scripting 3 Client-Server Architecture In a client-server architecture, computation is done either in the client or in the server.
Introduction to scripting
Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU.
Javascript and the Web Whys and Hows of Javascript.
4.1 JavaScript Introduction
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Scripting Languages.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
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 Gordon Tian
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
1 Lecture #6 Dynamic Web Documents HAIT Summer 2005 Shimrit Tzur-David.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Lecture 9 The Basics of JavaScript Boriana Koleva Room: C54
1 Representation and Management of Data on the Web Javascript.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
JavaScript, Fourth Edition
JS1-1 Introduction to JavaScript (JavaScript 1) Xingquan (Hill) Zhu
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
COP 3813 Intro to Internet Computing Prof. Roy Levow Lecture 4 JavaScript.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
CGS 3066: Web Programming and Design Spring 2016 Introduction to JavaScript.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
1 Browser Scripting JavaScript. 2 Introduction 3 Client-Server Architecture In a client-server architecture, computation is done either in the client.
CGS 3066: Web Programming and Design Spring 2017
>> Introduction to JavaScript
“Under the hood”: Angry Birds Maze
Chapter 4 Client-Side Programming: the JavaScript Language
JavaScript Syntax and Semantics
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
JavaScript.
JavaScript and Ajax (Expression and Operators)
JavaScript an introduction.
WEB PROGRAMMING JavaScript.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
CS5220 Advanced Topics in Web Programming JavaScript Basics
University of Kurdistan
CS105 Introduction to Computer Concepts
CS3220 Web and Internet Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
An Introduction to JavaScript
JavaScript: Introduction to Scripting
PHP an introduction.
Web Programming– UFCFB Lecture 13
CS3220 Web and Internet Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

1 Browser Scripting JavaScript

2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate

3 Introduction

4 Client-Server Architecture In a client-server architecture, computations are done either in the client or in the server (or both) In some cases, we can choose whether to perform the computation in the client or the server side - For example, validating forms There are cases where we cannot choose where to perform the computation - For example, accessing a database

5 Client Side Technologies JavaScript - Developed by Netscape, standardized by ECMA - Supported by all browsers (although not all support the standard) VBScript - Developed by Microsoft - Supported only by Microsoft Internet Explorer - A light version of Microsoft Visual Basic Java Applets - Developed by Sun Flash - Developed by Macromedia (acquired by Adobe in 2005)

6 About Applets An applet is a Java class that runs in a frame that is embedded in a Web page When a browser loads the Web page, the applet byte-code (.class file) is downloaded to the client box and executed by the browser Commonly used for games, graphics, etc.

7

8 Browser Scripting Browser scripts are procedural programs embedded inside HTML script Can read and manipulate HTML elements, CSS properties, and the browser itself

Web browser HTML Page: …code..… Internet HTML/HTTP TCP/IP HTML/HTTP TCP/IP Web (HTTP) Server HTML pages with embedded script built-in Script interpreter Web Architecture for Scripts ClientServer

10 Why are Scripts Needed? Generating HTML content dynamically Monitoring and responding to user events Validating forms before submission Manipulating HTTP cookies Interaction among the frames and windows of the browser Interacting with the server (w/o browser refresh)

11 JavaScript History Introduced in Netscape 2 (1996) Standardized by ECMA under the name ECMAScript ( ) The latest version is ECMAScript 4, and it is equivalent to JavaScript 2.0

12 JavaScript Basics

13 JavaScript is NOT Java! JavaScript is not compiled JavaScript is typically executed by Web browsers and not as stand-alone applications JavaScript and Java have some similarity in syntax The choice of the name is mainly for historical reasons

14 Dynamic HTML Content: Example 1 JS Example Before the script document.write(' In the script ') After the script

15

16 Dynamic HTML Content: Example 2 JS Example Before the script document.write(new Date().toLocaleString()) After the script

17 Dynamic HTML Content: Example 3 Hello and var hours = new Date().getHours(); if (hours < 10) { document.write("good morning") } else {document.write("good day") }.

18 Basic Constructs Statement blocks - Semicolon (;) is optional at end of line var x=5 document.write(x); var x=5, y=7; document.write(x+y); if (condition) {statements if true} else {statements if false} Conditions: if, if-else, ?:, switch x= (y>0)? y:0 Loops: for, while, do-while while (condition) {statements}

19 Variables Variables are not typed! (but values are) - var x = 5; x="abcd";... Thus, the value of a variable is characterized by both value and type Variables are declared with var keyword: - var x; var y=5; - Without var, a variable is considered global A variable name consists of letters, digits, and underscores (_), - Does not begin with a digit

20 Data Types Values have one of the following types: - number: 5, 2.3, 0xFF, 6.67e-11 - object: new Date() Arrays: [1,"ab ba",17.234] null - string: "Hello World" - boolean: true, false - function (discussed later) - undefined: no value assigned... You can use typeof(x) to get the type of x : number, string, object...

21 Some of the Reserved Words abstract as break case catch class const continue default delete do in instanceof interface is namespace new null package private public return else export extends false final finally for function if implements import static super switch this throw true try typeof use var void while with

22 Operators Arithmetic: * / % Comparison: == != === !== > >= < <= Logical: & && | || ! Bitwise: & | ^ ~ > >>> String: + Assignments: = += -= *= /= <<= |=...

23 Types of Equality The equals == ( != ) checks if both operands are equal after performing type conversion The equals === ( !== ) checks if both operands are of the same type and equal Example: - Is 34 == "34" ? Is 34 == "3"+"4" ? - Is 34 === "3"+"4" ? Is 34 !== "3"+"4" ?

24 An Example for (var counter = 1 ; counter <= 8 ; ++counter) { var fontsize = counter + 10; fontsize+="pt"; document.write(" " + "Font size " + fontsize + " "); }

25

26 Functions

27 Functions JavaScript functions are special constructs with the operator () Syntax: function fname(args...) {statements} Usually, functions are defined at the head - Guarantees that functions are declared before used Some functions are predefined - For example, parseInt(string) Functions can return values

28 Function Example function add(x,y) { return x+y; } sum = add(4,5); document.write("4+5="+sum);

29 Function Values Parameters are passed to (and return from) functions by value - Assignment does not change the original parameter Objects are not copied but rather act as pointers - That is, properties of an object can be changed when given as an argument of a function

30 Undeclared Arguments Function may receive arguments without declaring them Within a function, its arguments are held in the arguments array - The ith argument is arguments[i] - The number of arguments is arguments.length Hence, it is possible to define functions that take any number of arguments

31 An Example What is the result of the following code? function myConcat(separator) { var result=""; // iterate through arguments for (var i=1; i<arguments.length; i++) { result += arguments[i] + separator; } return result; } con = myConcat(", ","red","orange","blue");

32 Predefined Functions JavaScript includes several predefined functions For example, - eval(code-string) – gets a string of JavaScript code, evaluates it and executes it It allows dynamic code execution - parseInt(string) – converts the beginning of string to an integer (or return NaN)

33 Variable Scopes JavaScript variables are recognized inside their declaration scope Hence, global variables should be declared outside the functions A variable declared in a function can also be global, if var is omitted

34 Objects and Arrays

35 Object Model JavaScript objects are similar to associative arrays That is, an object associates identifiers (e.g., firstName ) with values (attributes) (e.g., "John" ) Those values may be other objects (nested objects) Those values can also be functions (methods) - e.g., function setPersonAge(age) {this.age = age} When o.f() is invoked, o can be referred to as this

36 Creating Objects Objects can be created in several ways: Object initializers Object assignments var theNissan = {make:"Nissan", year:2003, color:"blue"} theMazda = { make:"Nissan" } theMazda.year = 2002; theMazda.color="black";

37 Creating Objects (cont) Object Constructors - Define a constructor function - Create the new object using new function car(make,year,color) { this.make = make this.year = year this.color = color } theHonda = new car("Honda", 2001, "green")

38 Defining Methods Methods are associated with objects just like attributes function niceString() { return " " + this.make + " "+ this.year + " " } theNissan = {make:"Nissan",year:2003,color:"blue",str:niceString}

39 Defining Methods (cont) function car(make,year,color) { this.make = make this.year = year this.color = color this.str = niceString } theHonda = new car("Honda", 2001, "green") theNissan = {make:"Nissan", year:2003, color:"blue"} theNissan.str = niceString;

40 Accessing Object Properties Object attributes can be accessed in several ways: - object.attName - object["attName"] Thus, object methods are invoked in Java/C++ style: - object.method(arguments) Alternatively: - object["method"](arguments)

41 The Complete Example function niceString() { return " " + this.make + " "+ this.year + " " } function car(make,year,color) { this.make = make; this.year = year; this.color = color; this.str = niceString } var theHonda = new car("Honda", 2001, "green"); document.write(theHonda.str());

42 Array Objects Arrays are supported as objects Attribute length Methods include: concat, join, pop, push, reverse, sort, shift,... Arrays can be passed to functions as arguments

43 Creating Arrays var a = ["red", "blue", "green"] - Allocates an array of 3 cells and initializes the values var b = new Array(5) - Allocates an array of 5 cells without initializing var c = new Array() - Creates a new empty array

44 Array Elements Array elements need not have the same type - arr1 = ["hello", 1, true] Java-like access: arr[i] Out-of-bounds assignments automatically enlarge the array - arr1[10] = 66 Multi-dimensional arrays are arrays of arrays - var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]]

45 Miscellaneous

46 JavaScript and XHTML Embedding JavaScript code inside XHTML may violate XML rules - e.g., x 2 One solution is to import JavaScript code from external files, e.g.: - Always a good habit... Another solution: wrap the code in an XML CDATA section

47 Wrapping Code in CDATA //<![CDATA[ regular JavaScript code... //]]>

48 The String Object JavaScript has a built-in String object - not the primitive string! Create a String object from a string primitive: - myString = new String("This is a string object") Extract the primitive string from a String object: - str = myString.valueOf()

49 String Common Methods charAt (index) charCodeAt(index) concat(string) fromCharCode(value1, value2, …) indexOf(substring, index) lastIndexOf(substring, index) slice(start, end) split(string) substr(start, length) substring(start, end) toLowerCase() toUpperCase() valueOf() match(regexp)

50 An Example - Format Verification What does the following function do? function getString() { var result = null; while(result==null) { var answer = prompt("Your first name:") if(answer!=null) { result = new String(answer); result = result.toLowerCase().match("^[a-z]+$"); } if(result==null) { alert("Don't mess with me!") } } return answer }

51 The Math Object The object Math is used for mathematical operations - E.g., Math.pow(x,2) Other useful functions: abs(x) round(x) ceil(x) floor(x) cos(x) sin(x) tan(x) exp(x) pow(x, y) sqrt(x) log(x) max(x, y) min(x, y) Math Also includes constants such as: Math.E, Math.PI

52 The with Statement Establishes the default object for a set of statements Within the set of statements, any property references that do not specify an object are assumed to be of the default object var a, x, y var r=10 with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI/2) }

53 The Date Object Create the current date: new Date() Create an arbitrary date: new Date( date-string ) Common methods of Date : getDate() getFullYear() getMonth() getDay getTime() getHours() getMinutes() getSeconds() getMilliseconds() toLocaleString()