Princess Nourah bint Abdulrahman University. Computer Sciences Department

Similar documents
Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

JavaScript Introduction

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

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

CGS 3066: Spring 2015 JavaScript Reference

CSS The web browser uses its own resources, and eases the burden on the server. It has fewer features than server side scripting.

CSC Web Programming. Introduction to JavaScript

HTML5 and CSS3 More JavaScript Page 1

Client-Side Web Technologies. JavaScript Part I

SEEM4570 System Design and Implementation Lecture 03 JavaScript

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

What is PHP? [1] Figure 1 [1]

CSCE 120: Learning To Code

Such JavaScript Very Wow

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

JavaScript Introduction

JavaScript Introduction

Working with JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

Coding in JavaScript functions

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

A Balanced Introduction to Computer Science, 3/E

Pace University. Fundamental Concepts of CS121 1

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

JScript Reference. Contents


JME Language Reference Manual

Chapter 2 Working with Data Types and Operators

The JavaScript Language

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

Functions, Randomness and Libraries

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

CS110: PROGRAMMING LANGUAGE I

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

JavaScript CS 4640 Programming Languages for Web Applications

Java+- Language Reference Manual

CSC Web Technologies, Spring Web Data Exchange Formats

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

5. JavaScript Basics

CMPT 100 : INTRODUCTION TO

JavaScript: The Basics

PHP. Interactive Web Systems

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

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

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript s role on the Web

EXERCISE: Introduction to client side JavaScript

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COMS 469: Interactive Media II

Web Site Design and Development JavaScript

JavaScript Introduction

So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS1520 Recitation Week 2

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

WINTER. Web Development. Template. PHP Variables and Constants. Lecture

Outcomes Week 2 Overview Describe the inputs, activities, and outputs of each step in the software development life cycle. Describe arithmetic, relati

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

CISC 1600 Lecture 2.4 Introduction to JavaScript

The pixelman Language Reference Manual. Anthony Chan, Teresa Choe, Gabriel Kramer-Garcia, Brian Tsau

COMS W4115 Programming Languages & Translators GIRAPHE. Language Reference Manual

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

Decision Making in C

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

<form>. input elements. </form>

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

Flow Control. CSC215 Lecture

JavaScript: Sort of a Big Deal,

Variables and Typing

INFS 2150 Introduction to Web Development and e-commerce Technology. Programming with JavaScript

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

Objectives. Introduction to JavaScript. Introduction to JavaScript INFS Peter Y. Wu, RMU 1

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

JQuery and Javascript

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

PHP by Pearson Education, Inc. All Rights Reserved.

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

CHIL CSS HTML Integrated Language

Place User-Defined Functions in the HEAD Section

Chapter 9: Simple JavaScript

AP CS Unit 3: Control Structures Notes

CHAPTER 6 JAVASCRIPT PART 1

MatchaScript: Language Reference Manual Programming Languages & Translators Spring 2017

Outline. Data and Operations. Data Types. Integral Types

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

CITS1231 Web Technologies. JavaScript

Typescript on LLVM Language Reference Manual

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Arrays Structured data Arrays What is an array?

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Transcription:

Princess Nourah bint Abdulrahman University 1

And use http://www.w3schools.com/

JavaScript

Objectives Introduction to JavaScript Objects Data Variables Operators Types Functions Events 4

Why Study JavaScript? JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages 5

Introduction JavaScript is THE scripting language of the Web (its role as the scripting language of the WWW). JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers, PCs, laptops, tablets, smart phones, and more. JavaScript is standards-based and the only language that runs in all web browsers. The -Script suffix suggests that it is not a real programming language, that a scripting language is less than a programming language 6

JavaScript is a Scripting Language JavaScript is a dynamic computer programming language. A scripting language is a lightweight programming language. JavaScript is code statements inserted into HTML pages to be executed by the web browser. Scripts in HTML must be inserted between <script> and </script> tags. Scripts can be put in the <body> and in the <head> section of an HTML page. 7

JavaScript Functions and Events is executed when the page loads. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Then we can write the script inside a function, and call the function when the event occurs. 8

Scripts in <head> and <body> You can place an unlimited number of scripts in your document, and you can have scripts in both the <body> and the <head> section at the same time. It is a common practice to put functions in the <head> section, or at the bottom of the page. This way they are all in one place and do not interfere with page content. Scripts can also be placed in external files. External files often contain code to be used by several different web pages. 9

JavaScript Can Change HTML Content One of many HTML methods is document.getelementbyid(). This example "finds" the HTML element with id="demo", and changes its content (innerhtml): Use the "id" attribute to identify the HTML element 10

Manipulating HTML Elements To access an HTML element from JavaScript, you can use the document.getelementbyid(id) method. Use the "id" attribute to identify the HTML element 11

Writing to The Document Output The example below writes a <p> element directly into the HTML document output 12

JavaScript Statements -1 JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do. This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML element with id="demo": document.getelementbyid("demo").innerhtml="hello Dolly"; Semicolon ; Semicolon separates JavaScript statements. Normally you add a semicolon at the end of each executable statement. Using semicolons also makes it possible to write many statements on one line. Ending statements with semicolon is optional in JavaScript. 13

JavaScript Statements -2 A computer program is a list of "instructions" to be "executed" by the computer. In a programming language, these program instructions are called statements. JavaScript is a programming language. JavaScript statements are separated by semicolon. 14

JavaScript Code JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is executed by the browser in the sequence they are written. Example document.getelementbyid("demo").innerhtml="hello Dolly"; document.getelementbyid("mydiv").innerhtml="how are you?"; 15

JavaScript Code Blocks JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket, and end with a right curly bracket. The purpose of a block is to make the sequence of statements execute together. A good example of statements grouped together in blocks, are JavaScript functions. Example function myfunction() { document.getelementbyid("demo").innerhtml="hello Dolly"; document.getelementbyid("mydiv").innerhtml="how are you?"; } 16

JavaScript is Case Sensitive JavaScript is case sensitive. Watch your capitalization closely when you write JavaScript statements: A function getelementbyid is not the same as getelementbyid. A variable named myvariable is not the same as MyVariable. 17

White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: var name="hege"; var name = "Hege"; Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("hello \ World!"); However, you cannot break up a code line like this: document.write \ ("Hello World!"); 18

Single line comments Comments will not be executed by JavaScript. Comments can be added to explain the JavaScript, or to make the code more readable. Single line comments start with //. // is used to prevent the execution of one of the codelines. // is placed at the end of a code line. The following example uses single line comments to explain the code: Example // Write to a heading: document.getelementbyid("myh1").innerhtml="welcome to my Homepage"; // Write to a paragraph: document.getelementbyid("myp").innerhtml="this is my first paragraph."; 19

Multi-Line Comments Multi line comments start with /* and end with */. The following example uses a multi line comment to explain the code: Example /* The code below will write to a heading and to a paragraph, and will represent the start of my homepage: */ document.getelementbyid("myh1").innerhtml="welcome to my Homepage"; document.getelementbyid("myp").innerhtml="this is my first paragraph."; 20

21

22

JavaScript: Reacting to Events -1.1 23

JavaScript: Reacting to Events -1.2 24

JavaScript: Changing HTML Content -2.1 25

JavaScript: Changing HTML Content -2.2 26

JavaScript: Changing HTML Images 3.1 27

JavaScript: Changing HTML Images 3.2 28

JavaScript Identifiers All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalvolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter Names can also begin with $ and _ (but we will not use it in this tutorial) Names are case sensitive (y and Y are different variables) Reserved words (like JavaScript keywords) cannot be used as names Note: JavaScript identifiers are case-sensitive. 29

JavaScript Variables JavaScript variables are "containers" for storing information: Example var x=5; var y=6; var z=x+y; 30

JavaScript Data Types String, Number, Boolean, Array, Object, Null, Undefined Example: var pi=3.14; var name="john Doe"; var answer='yes I am!'; Declaring (Creating) JavaScript Variables Creating a variable in JavaScript is most often referred to as "declaring" a variable. declare JavaScript variables with the var keyword: var carname; After the declaration, the variable is empty (it has no value). To assign a value to the variable, use the equal sign: carname="volvo"; However, you can also assign a value to the variable when you declare it: var carname="volvo"; 31

32

One Statement, Many Variables You can declare many variables in one statement. Just start the statement with var and separate the variables by comma: var name="doe", age=30, job="carpenter"; Your declaration can also span multiple lines: var name="doe", age=30, job="carpenter"; 33

JavaScript Data Types JavaScript variables can hold many data types: numbers, strings, arrays, objects and more: 34

In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer cannot safely implement the JS code 35

JavaScript Has Dynamic Types JavaScript has dynamic types. This means that the same variable can be used as different types: 36

37

The typeof Operator You can use the JavaScript typeof operator to find the type of a JavaScript variable: 38

JavaScript Arrays The following code creates an Array called cars: var cars=new Array(); cars[0]="saab"; cars[1]="volvo"; cars[2]="bmw"; or (condensed array): var cars=new Array("Saab","Volvo","BMW"); or (literal array): var cars=["saab","volvo","bmw"]; 39

JavaScript Objects An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas: var person={firstname:"john", lastname:"doe", id:5566}; The object (person) in the example above has 3 properties: firstname, lastname, and id. Spaces and line breaks are not important. Your declaration can span multiple lines: var person={ firstname : "John", lastname : "Doe", id : 5566 }; 40

JavaScript Objects 41

Undefined and Null - Declaring Variable Types Undefined is the value of a variable with no value. Variables can be emptied by setting the value to null; Example cars=null; person=null; When you declare a new variable, you can declare its type using the "new" keyword: var carname=new String; JavaScript variables are all var x= new Number; var y= new Boolean; objects. When you declare a var cars= new Array; variable you create a new var person= new Object; object. 42

Creating JavaScript Objects Almost "everything" in JavaScript is an object. Strings, Dates, Arrays, Functions. You can also create your own objects. 43

JavaScript Arithmetic 44 Example

JavaScript Functions 45

JavaScript Operators 46

JavaScript Comparison and Logical Operators 47

48

Calling a Function with Arguments 49

50

Functions With a Return Value This is possible by using the return statement. When using the return statement, the function will stop executing, and return the specified value. Syntax function myfunction() { var x=5; return x; } 51

52

JavaScript Scope In JavaScript, objects and functions, are also variables. In JavaScript, scope is the set of variables, objects, and functions you have access to. Variables declared within a JavaScript function, become LOCAL to the function. Local variables have local scope: They can only be accessed within the function variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web page can access it. 53

Local JavaScript Variables 54

Global JavaScript Variables 55

Global Variables in HTML In HTML, the global scope is the window object: All global variables belong to the window object 56

JavaScript Events 57

JavaScript Math Object - 1 The Math object allows you to perform mathematical tasks. The Math object includes several mathematical methods. Math.random(); // returns a random number Math.min() // can be used to find the lowest value in a list of arguments Math.max() // can be used to find the lowest highest value in a list of arguments Math.round() //rounds a number to the nearest integer Math.ceil() // rounds a number up to the nearest integer Math.floor() // rounds a number down to the nearest integer 58

JavaScript Math Object - 2 Math.E; // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E Math.pow(x,y) //Returns the value of x to the power of y 59

60

JavaScript If...Else Statements Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed 61

62

63

Different Kinds of Loops JavaScript supports different kinds of loops: for - loops through a block of code a number of times for/in - loops through the properties of an object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true 64

JavaScript Loops 65

66

The For/In Loop The JavaScript for/in statement loops through the properties of an object: Example var person={fname:"john",lname:"doe",age:25}; for (x in person) { txt=txt + person[x]; } 67

68

JavaScript Errors - Throw and Try to Catch The try statement lets you to test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. 69

JavaScript try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The JavaScript statements try and catch come in pairs. Syntax try { //Run some code here } catch(err) { //Handle errors here } 70

71

72

JavaScript Closures self-invoking functions Try 73

JavaScript Nested Functions Try 74