JAVASCRIPT. Computer Science & Engineering LOGO

Similar documents
Chapter 2 Working with Data Types and Operators

CSC Web Programming. Introduction to JavaScript

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

5/19/2015. Objectives. JavaScript, Sixth Edition. Introduction to the World Wide Web (cont d.) Introduction to the World Wide Web

By the end of this section of the practical, the students should be able to:

3 The Building Blocks: Data Types, Literals, and Variables

A.A. 2008/09. Why introduce JavaScript. G. Cecchetti Internet Software Technologies

Working with JavaScript

CGS 3066: Spring 2015 JavaScript Reference

Chapter 2: Using Data

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

Dynamism and Detection

A Balanced Introduction to Computer Science, 3/E

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

COMS 469: Interactive Media II

JavaScript: Introduction to Scripting

Chapter 2: Functions and Control Structures

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Client-Side Web Technologies. JavaScript Part I

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Visual C# Instructor s Manual Table of Contents

The first sample. What is JavaScript?

Full file at

Lesson 3: Basic Programming Concepts

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

Such JavaScript Very Wow

JavaScript: Introductionto Scripting

CSCE 120: Learning To Code

Exercise 1: Basic HTML and JavaScript

Typescript on LLVM Language Reference Manual

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

JavaScript CS 4640 Programming Languages for Web Applications

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

CHAD Language Reference Manual

Web Site Design and Development JavaScript

Program Design Phase. Algorithm Design - Mathematical. Algorithm Design - Sequence. Verify Algorithm Y = MX + B

Constants and Variables

JavaScript I Language Basics

4. Inputting data or messages to a function is called passing data to the function.

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Course PJL. Arithmetic Operations

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

The C++ Language. Arizona State University 1

easel LANGUAGE REFERENCE MANUAL

SECTION II: LANGUAGE BASICS

JME Language Reference Manual

JavaScript: More Syntax

CHAPTER 3 BASIC INSTRUCTION OF C++

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Petros: A Multi-purpose Text File Manipulation Language

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Full file at

JavaScript code is inserted between tags, just like normal HTML tags:

Chapter 2: Using Data

Command-driven, event-driven, and web-based software

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

DaMPL. Language Reference Manual. Henrique Grando

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

X Language Definition

Lecture 14. Introduction to JavaScript. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

Programming with Java

Operators. Java operators are classified into three categories:

Programming language components

Java+- Language Reference Manual

CHIL CSS HTML Integrated Language

Lecture 2. The variable 'x' can store integers, characters, string, float, boolean.

Place User-Defined Functions in the HEAD Section

COMS 469: Interactive Media II

Introduction to Programming Using Java (98-388)

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

JAVA Programming Fundamentals

JavaScript: Introduction, Types

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Chapter 17. Fundamental Concepts Expressed in JavaScript

PIC 40A. Midterm 1 Review

Python Programming Exercises 1

Programming for Engineers Introduction to C

c122mar413.notebook March 06, 2013

egrapher Language Reference Manual

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

2 nd Week Lecture Notes

Language Reference Manual simplicity

Chapter 02: Using Data

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

The Warhol Language Reference Manual

FRAC: Language Reference Manual

Cellular Automata Language (CAL) Language Reference Manual

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Coding in JavaScript functions

In addition to the primary macro syntax, the system also supports several special macro types:

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

An Introduction to MATLAB

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Sprite an animation manipulation language Language Reference Manual

Transcription:

JAVASCRIPT

JavaScript and Client-Side Scripting When HTML was first developed, Web pages were static Static Web pages cannot change after the browser renders them HTML and XHTML could only be used to produce static documents. JavaScript Client-side scripting language that allows Web page authors to develop interactive Web pages and sites

JavaScript and Client-Side Scripting Client-side scripting: Scripting language that runs on a local browser (on the client tier) JavaScript gives you the ability to: Turn static Web pages into applications such as games or calculators Change the contents of a Web page after a browser has rendered it Create visual effects such as animation Control the Web browser window itself

The <script> Element Scripts JavaScript programs contained within a Web page <script> element Tells the Web browser that the scripting engine must interpret the commands it contains. The type attribute tells the browser which scripting language and which version of the scripting language is being used.

Understanding JavaScript Objects Object Programming code and data that can be treated as an individual unit or component Procedures Individual statements used in a computer program grouped into logical units Used to perform specific tasks Methods Procedures associated with an object For example: loan.calcpayments();

Understanding JavaScript Objects Property Piece of data associated with an object Assign a value to a property using an equal sign. Argument loan.interest =.08; Information that must be provided to a method. Providing an argument for a method is called passing arguments loan.calcpayments(800);

The write() and writeln() Document object represents the content of a browser s window You create new text on a Web page with the write() method or the writeln() method of the Document object Both methods require a text string as an argument. Text string or literal string: text that is contained within double or single quotation marks. document.write( Welcome to Javascript!");

Case Sensitivity in JavaScript JavaScript is case sensitive. Within JavaScript code, object names must always be all lowercase.

Comments to a JavaScript Program Comments Nonprinting lines that you place in your code to contain various types of remarks Line comment Hides a single line of code Add two slashes // before the comment text Block comments Hide multiple lines of code Add /* before the first character you want included in the block and */ after the last character in the block

Structuring JavaScript Code When you add JavaScript code to a document, you need to follow certain rules regarding the placement and organization of that code The following sections describe some important rules to follow when structuring JavaScript code. Include as many script sections as you like within a document. When you include multiple script sections in a document, you must include a <script> element for each section.

Placing JavaScript in the Document You can place <script> elements in either the document head or document body Good idea to place as much of your JavaScript code as possible in the document head Important to put JavaScript code in document head When code performs behind-the-scenes tasks required by script sections in the document body

Placing JavaScript in the Document <head> <Script language= JavaScript > Javascript Comments </script> </head>

Placing JavaScript in the Document <HTML> <HEAD> <script language="javascript" > document.write( What is your name? ); </script> </HEAD> <BODY> content of page </BODY> </HTML>

Creating a JavaScript Source File JavaScript source file Usually designated by the file extension.js Does not contain a <script> element To access JavaScript code saved in an external file, assign to the src attribute of the <script> element the URL of the JavaScript source file Use a combination of embedded JavaScript code and JavaScript source files in your documents

Creating a JavaScript Source File <Script SRC= filejavascript.js Language="javascript" > </Script> JavaScript program

Data Types and Operators Variable Specific location in computer s memory Before using a variable: Write a statement that creates the variable and assigns it a name Variable names are case sensitive myvariable, myvariable, MyVariable, and MYVARIABLE are all different variables

Declaring and Initializing Variables Use the reserved keyword var to create variables To create a variable named myvariable: Declaring a variable var myvariable; Using a statement to create a variable Initializing a variable Assigning a specific value to it Can be done when you declare the variable var variable_name = value;

Declaring and Initializing Variables Assignment operator Equal sign (=) Assigns the value on the right side of expression to the variable on the left side of expression. Value assigned to a variable: Literal string must be enclosed in quotation marks var myname = "Don ; Numeric value is not enclosed in quotation marks.

Displaying Variables Can declare multiple variables using a single var keyword Ex: var customername = "Don Gosselin", orderquantity = 100, salestax =.05; Can assign value of one variable to another Ex: var salestotal; var curorder = 40; salestotal = curorder;

Displaying Variables To print a variable, pass variable name to document.write() or Example: document.writeln() method document.write("<p>your sales total is $ + salestotal + ".</p>");

Modifying Variables To change a variable s value, use a statement with variable s name, equal sign, and new value Example: var salestotal = 40; document.write("<p>your sales total is $" + salestotal + ".</p>"); var shipping = 10; salestotal = salestotal + shipping; document.write("<p>your sales total plus shipping is $" + salestotal + ".</p>");

Modifying Variables

Data Types Data type Category of information that a variable contains. Primitive types Data types that can be assigned only a single value.

Data Types JavaScript supports two numeric data types: Integers and floating-point numbers Integer Positive or negative number with no decimal places Floating-point number Decimal places (or written in exponential notation) Exponential notation, or scientific notation Shortened format for writing very large numbers or numbers with many decimal places

Boolean Values Boolean value Logical value of true or false In JavaScript, words true and false indicate Boolean values Example var repeatcustomer = true; var corporatediscount = false; document.write("<p>repeat customer: " + repeatcustomer + "</p>"); document.write("<p>corporate discount: " + corporatediscount + "</p>");

Boolean Values

Arrays Array: Set of data represented by a single variable name

Declaring and Initializing Arrays Element: each piece of data in an array Example: Create an array named hospitaldepts[] that has 10 elements var hospitaldepts = new Array(10); Assign value to first element in: hospitaldepts[] hospitaldepts[0] = "Anesthesia"; Can assign value to elements when array is created hospitaldepts = new Array("Anesthesia", "Molecular Biology", "Neurology");

Accessing Element Information To access an element s value, include brackets and element index Examples document.writeln(hospitaldepts[0]); // prints "Anesthesia" document.writeln(hospitaldepts[1]); // prints "Molecular Biology" document.writeln(hospitaldepts[2]); // prints "Neurology"

Modifying Elements To modify values in existing array elements, include brackets and element index Examples hospitaldepts[0] = "Anesthesia"; // first element hospitaldepts[1] = "Molecular Biology"; // second element hospitaldepts[2] = "Neurology"; // third element

The Number of Elements in an Array Determining the Number of Elements in an Array length property of Array class returns the number of elements in an array Syntax array_name.length;

The Number of Elements in an Array Example <script> var arr= new Array(); arr[0]= "thu hai"; arr[1]= "Thu ba"; arr[2]= "Thu tu"; arr[3]= "Thu nam"; arr[4]= "Thu sau"; arr[5]= "Thu bay"; for(i=0; i<=5; i++) document.write(arr[i]+ "<br>"); document.write(arr.length+ "<br>");//6 </script>

Arithmetic Operators Used to perform mathematical calculations Addition, subtraction, multiplication, division, etc.

Arithmetic Operators Prefix operator Placed before a variable Postfix operator Placed after a variable

Assignment Operators

Comparison and Conditional Operators

Logical Operators Logical operators Compare two Boolean operands for equality

Strings Text string is text contained within double or single quotation marks Can use text strings as literal values or assign them to a variable Empty string Zero-length string value Valid value for literal strings

String Operators Operators used to combine two strings Concatenation operator (+) Example: var destination = "Jakarta"; var location = "Indonesia"; destination = destination + " is in " + location; Compound assignment operator (+=) var destination = "Jakarta"; destination += " is in Indonesia";

Escape Characters and Sequences

Functions, Events, and Control Structures

Working with Functions Functions Procedures similar to the methods associated with an object Make it possible to treat a related group of JavaScript statements as a single unit Must be contained within a <script> element

Working with Functions Syntax: function nameoffunction(parameters) { statements; } Parameter Variable that is used within a function Placed in parentheses following a function name To execute a function, you must invoke, or call

Working with Functions return statement: Returns a value to the statement that called the function Example function averagenumbers(a, b, c) { } var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result;

Variable Scope Global variable One that is declared outside a function and is available to all parts of your program. Local variable Declared inside a function and is only available within the function in which it is declared. When a program contains a global variable and a local variable with the same name. The local variable takes precedence when its function is called.

Using Built-in JavaScript Functions ALERT BOX: alert("yourtext"); The user will need to click "OK" to proceed.

Using Built-in JavaScript Functions CONFIRM BOX: confirm("yourtext"); The user needs to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns the value true. If the user clicks "Cancel", the box returns the value false.

Using Built-in JavaScript Functions Example:

Using Built-in JavaScript Functions PROMPT BOX: prompt("yourtext","defaultvalue"); If the user clicks "OK" the prompt box returns the entry. If the user clicks "Cancel" the prompt box returns null.

Using Built-in JavaScript Functions settimeout(): Set time period after which the command will be executed. Syntax: IdTime=setTimeout( Command JavaScript, delaytime); cleartimeout(): Cancel time set by the settimeout () Syntax : cleartimeout(idtime );

Using Built-in JavaScript Functions

Using Built-in JavaScript Functions

Understanding Events Event Specific circumstance (tình huống) that is monitored by JavaScript And that your script can respond to in some way You can use JavaScript events to allow users to interact (tương tác) with your Web pages Most common events are user actions.

Understanding Events

Working with Elements and Events Event handler Code that executes in response to a specific event Included as an attribute of the element that initiates the event <element event_handler ="JavaScript code"> Event handler names are the same as the name of the event itself, plus a prefix of on <img src=saobang.jpg onmouseout= doihinh() >

Working with Elements and Events JavaScript, Fourth Edition 53

Working with Elements and Events Example <input type="button" onclick="window.alert('you clicked a button!')"> window.alert() method Displays a pop-up dialog box with an OK button. You can include multiple JavaScript statements in an event handler, As long as semicolons separate the statements.

Working with Elements and Events Example: calculator program Use push buttons and onclick event handlers Use a variable named inputstring to contain the operands and operators of a calculation Calculation is performed using the eval() function

if Statements Syntax: if (<conditional>) { statement 1; statement 2; }

if Statements if else if(<conditional>) { Block statement 1; } else { Block statement 2; }

if Statements if else nested: if(<conditional 1>) { block statement 1; } else if (< conditional 2>) { Khối lệnh 2 ;} else {khối lệnh 3 }

if Statements <script language="javascript"> a=eval(prompt("nhap canh a")); b=eval(prompt("nhap canh b")); c=eval(prompt("nhap canh c")); if(a+b<c b+c<a c+a<b) alert("khong phai tam giac") else if(a==b&&b==c&&c==a) alert("tam giac đều") ; else if(a==b b==c c==a) alert("tam giac cân"); else alert("tam giác thuong"); </script>

Switch...Case Statements Switch...Case Switch(expression){ case value1: statement1 ; break; case value2: statement2 ; break; case valuek: statementk ; break; default : statementk+1 ;}

Switch...Case Statements <script> t=prompt( "nhap thang: "); switch (eval(t)) { case 1: case 3: case 5: case 7: case 8 : case 10: case 12: alert("thang "+ t+ " co 31 ngay"); break; case 2: alert("thang "+t + " co 28 ngay"); break; case 4: case 6: case 9: case 11: alert("thang "+t +" co 30 ngay"); break; default: alert("khong co thang nay"); }</script>

For Statements Syntax: For(Exp 1; Exp 2; Exp 3) { statement; }

For Statements <Script language="javascript"> var n, m, i, j; m=prompt("nhap so dong"); n=prompt("nhap so cot"); document.write("<table width=50% border=1>"); for(i=1;i<=m;i++) { document.write("<tr>"); for(j=1;j<=n;j++) document.write("<td>" + i + j +"</td>"); document.write("</tr>"); } document.write("</table>");

While Statement Syntax: While(expression) { Statement 1; } Statement 2;

do while statement Syntax: do { Statement 1; } While(Expression); Statement 2;

do while statement <script language="javascript"> var input; do { input=prompt( Nhập một số bấy kỳ, nhập 99 đế thóat ) if(isnan(input) { document.write( Dữ liệu không hợp lệ, nhập số ); break; } }while (input!=99 ) </script>

for in statement Syntax: for ( variable in Object) { Statement ; }

for in statement Example: <body> <script> obj= new Array() ; obj[0]="hello"; obj[1]="world" ; for(i in obj) document.write(obj[i]); </script> </body>