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

Similar documents
Introduction to JavaScript

JavaScript Introduction

<form>. input elements. </form>

JavaScript s role on the Web

Just add an HTML comment tag <!-- before the first JavaScript statement, and an end-of comment tag --> after the last JavaScript statement, like this:

JavaScript Introduction

The first sample. What is JavaScript?

CGS 3066: Spring 2015 JavaScript Reference

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Session 16. JavaScript Part 1. Reading

Session 6. JavaScript Part 1. Reading

CITS1231 Web Technologies. JavaScript

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

CISC 1600 Lecture 2.4 Introduction to JavaScript

Outline. Introduction to JavaScript Resources What is JavaScript? JavaScript in web pages

CSC Web Programming. Introduction to JavaScript

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

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Web Programming/Scripting: JavaScript

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

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

Syllabus - July to Sept

Q1. What is JavaScript?

Programing for Digital Media EE1707. Lecture 3 JavaScript By: A. Mousavi and P. Broomhead SERG, School of Engineering Design, Brunel University, UK

CHAPTER 6 JAVASCRIPT PART 1

Learning JavaScript. A C P K Siriwardhana, BSc, MSc

Note: Java and JavaScript are two completely different languages in both concept and design!

JavaScript Introduction

JavaScript CS 4640 Programming Languages for Web Applications

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

Unit 20 - Client Side Customisation of Web Pages. Week 4 Lesson 5 Fundamentals of Scripting

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript is described in detail in many books on the subject, and there is excellent tutorial material at

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

Working with JavaScript

CSC 337. JavaScript Object Notation (JSON) Rick Mercer

Produced by. App Development & Modeling. BSc in Applied Computing. Eamonn de Leastar

COMS 469: Interactive Media II

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

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

introjs.notebook March 02, 2014

PIC 40A. Lecture 10: JS: Wrapper objects, Input and Output, Control structures, random numbers. Copyright 2011 Jukka Virtanen UCLA 1 04/24/17

<script type="text/javascript"> script commands </script>

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

SEEM4570 System Design and Implementation Lecture 03 JavaScript

Exercise 1: Basic HTML and JavaScript

c122mar413.notebook March 06, 2013

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

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

JAVASCRIPT. sarojpandey.com.np/iroz. JavaScript

CSCE 120: Learning To Code

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

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

Lecture 8: JavaScript

5. JavaScript Basics

HTML 5 and CSS 3, Illustrated Complete. Unit L: Programming Web Pages with JavaScript

Place User-Defined Functions in the HEAD Section

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Programming language components

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CSC Software I: Utilities and Internals. Programming in Python

Then there are methods ; each method describes an action that can be done to (or with) the object.

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:

Mobile Site Development

JavaScript Basics. The Big Picture

Chapter 17. Fundamental Concepts Expressed in JavaScript

Operators. Java operators are classified into three categories:

JQuery and Javascript

Chapter 9: Simple JavaScript

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Chapter 2: Functions and Control Structures

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

Object-Oriented Programming

Client-Side Web Technologies. JavaScript Part I

Web Development & Design Foundations with HTML5

CMPT 100 : INTRODUCTION TO

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Loops/Confirm Tutorial:

1. Cascading Style Sheet and JavaScript

JavaScript Syntax. Web Authoring and Design. Benjamin Kenwright

HTML5 and CSS3 More JavaScript Page 1

CMPT 125: Lecture 3 Data and Expressions

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

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

For loops and Window Objects:

(Refer Slide Time: 01:40)

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

Tutorial 10: Programming with JavaScript

Full file at C How to Program, 6/e Multiple Choice Test Bank

JavaScript: The Basics

Enhancing Web Pages with JavaScript

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 12

Elementary Computing CSC 100. M. Cheng, Computer Science

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

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Transcription:

What is Java Script? CMPT 165: Java Script Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University November 7, 2011 JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language (a lightweight programming language). It is interpreted and thus does not required preliminary compilation. JavaScript may be embedded directly into HTML pages or in an external file 1 CMPT 165: Introduction to the Internet and the WWW: Java Script 2 What Can JavaScript do? Writing to The HTML Document JavaScript provides a tool to program for the web. It s simple syntax makes it suitable for people that are not necessarily programmers. You can use JavaScript to handle events: when something happens (an event), do something else (handle it). Example events can be: a page has finished loading or a user clicks on an HTML element (or form control) JavaScript can: read and write HTML elements change the content of an existing HTML element validate data before it is submitted to a server, saving the server from extra processing. detect the visitor s browser and load another page specifically designed for that browser store and retrieve information on the visitor s computer (create cookies) CMPT 165: Introduction to the Internet and the WWW: Java Script 3 To insert a JavaScript into an HTML page, and have it executed by the browser, write it inside the <script>... tags. Use the type attribute to define the scripting language. This example writes a <p> element with current date information to the HTML document: <h1>my First Web Page</h1> document.write("<p>" + Date() + "</p>"); In general, avoid using document.write() since it will overwrite the entire HTML page. CMPT 165: Introduction to the Internet and the WWW: Java Script 4

Changing HTML Element Content Document Object Model The example below writes the current date into an existing <p> element: <h1>my First Web Page</h1> <p id="demo"></p> To manipulate HTML elements JavaScript uses the DOM method getelementbyid(). This method accesses the element with the specified id. The DOM (Document Object Model) allows you to dynamically access and update the content, structure and style of HTML documents. This is done by accessing HTML objects or elements, as well as their styles and attributes. document.getelementbyid("demo").innerhtml=date() If the original HTML paragraph had been <p id="demo">this is a paragraph.</p> the browser would have repaced This is a paragraph with the current date. CMPT 165: Introduction to the Internet and the WWW: Java Script 5 CMPT 165: Introduction to the Internet and the WWW: Java Script 6 Where to put JavaScript in the HTML document? JavaScript can be put in the and in the sections of an HTML page. In the above example, the JavaScript was placed in the body and at the bottom of the page to make sure it was not executed before the <p> element is created. JavaScripts in an HTML page will be executed when the page loads. This is not always what we want. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. In this case, we can put the script inside a function. Events are normally used in combination with functions: call a function when an event occurs. CMPT 165: Introduction to the Internet and the WWW: Java Script 7 JavaScript in the... This example calls a function when a button is clicked: function displaydate() document.getelementbyid("demo").innerhtml=date(); <h1>my First Web Page</h1> <p id="demo"></p> <button type="button" onclick="displaydate()">display Date</button> It is a common practice to put all 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. 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. CMPT 165: Introduction to the Internet and the WWW: Java Script 8

Using an External JavaScript JavaScript Statements JavaScript can also be placed in external files, allowing code to be used on several different web pages. External JavaScript files have the file extension.js. To use an external script, assign the type and src attributes of the <script> tag as follows: <script type="text/javascript" src="xxx.js"> Place the script exactly where you normally would write the script. CMPT 165: Introduction to the Internet and the WWW: Java Script 9 JavaScript is a sequence of statements to be executed by the browser. A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do. Unlike HTML, JavaScript is case sensitive: watch your use of upper and lower case letters when you write JavaScript statements or create/call variables, objects and functions. This JavaScript statement tells the browser to write Hello Dolly to the web page: document.write("hello Dolly"); It is normal (though optional) to add a semicolon at the end of each executable statement. Though it is optional to add a semicolon at the end of a statement (since the browser interprets the end of the line as the end of the statement), using semicolons makes it possible to write multiple statements on one line. CMPT 165: Introduction to the Internet and the WWW: Java Script 10 JavaScript Code JavaScript Blocks JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is executed by the browser in the sequence they are written. This example will write a heading and two paragraphs to a web page: document.write("<h1>this is a heading</h1>"); document.write("<p>this is a paragraph.</p>"); document.write("<p>this is another paragraph.</p>"); 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. The above example could have been written as a block of code. document.write("<h1>this is a heading</h1>"); document.write("<p>this is a paragraph.</p>"); document.write("<p>this is another paragraph.</p>"); Though this example is not very useful, it demonstrates the use of a block. Normally a block is used to group statements together in a function or in a condition (where a group of statements should be executed if a condition is met). CMPT 165: Introduction to the Internet and the WWW: Java Script 11 CMPT 165: Introduction to the Internet and the WWW: Java Script 12

JavaScript Comments JavaScript Variables Comments can be added to explain JavaScript code, or to make the code more readable. Single line comments start with //. Example: // Write a heading document.write("<h1>this is a heading</h1>"); // Write two paragraphs: document.write("<p>this is a paragraph.</p>"); document.write("<p>this is another paragraph.</p>"); They may also be used at the end of a line: document.write("hello"); // Write "Hello" Multi-line comments start with /* and end with */. Example: /* The code below will write one heading and two paragraphs */ document.write("<h1>this is a heading</h1>"); document.write("<p>this is a paragraph.</p>"); document.write("<p>this is another paragraph.</p>"); Consider the algebraic expression: z = x + y. The value z will depend on x and y, that is, all are variables, and the result of the expression z will depend on the values held by x and y. Variables can be used to hold values (e.g. x=5) or expressions (e.g. z=x+y). As with algebra, you can do arithmetic operations with JavaScript variables: y=x-5; z=y+5; A variable name can be short, like x, or a more descriptive, like favoritecolor. Rules for JavaScript variable names: as with anything in JavaScript, variable names are case sensitive (y and Y are two different variables) variable names must begin with a letter or the underscore character CMPT 165: Introduction to the Internet and the WWW: Java Script 13 CMPT 165: Introduction to the Internet and the WWW: Java Script 14 can t be a reserved word (a word with another meaning in JS syntax) You can refer to a variable by its name to display or change its value during the execution of a script. Declaring (Creating) JavaScript Variables Creating variables in JavaScript is referred to as declaring variables (akin to declarations in CSS). You declare JavaScript variables with the keyword var var x; var favoritecolor; After the declaration shown above, the variables are empty (they hold no values). It is possible to assign values to the variables when they are declared: var x=5; var favoritecolor="blue"; When you assign a text value to a variable (a string), use quotes around the value. If you redeclare a JavaScript variable, it will not lose its value. CMPT 165: Introduction to the Internet and the WWW: Java Script 15 CMPT 165: Introduction to the Internet and the WWW: Java Script 16

Local and Global JavaScript Variables Assigning Values to Undeclared JavaScript Variables A variable declared within a JavaScript function can only be accessed within that function. That is, it is local in scope. You can have local variables with the same name in different functions, because their scope is limited to the function in which they are declared. Variables declared outside a function become global and can be accessed anywhere on the web page (including functions). Global variables are destroyed when you close the page. If you declare a variable without using var, the variable always becomes global. If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. These statements: x=5; favoritecolor="blue"; will declare the variables x and favoritecolor as global variables (if they don t already exist). CMPT 165: Introduction to the Internet and the WWW: Java Script 17 CMPT 165: Introduction to the Internet and the WWW: Java Script 18 JavaScript Operators JavaScript Arithmetic Operators The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. For example: y=5; z=2; x=y+z; The value of x, after the execution of the statements above, is 7. Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5, the table below explains the arithmetic operators: Operator Description Example + Addition x=y+2 x=7 y=5 - Subtraction x=y-2 x=3 y=5 * Multiplication x=y*2 x=10 y=5 / Division x=y/2 x=2.5 y=5 % Modulus x=y%2 x=1 y=5 ++ Increment x=++y x=6 y=6 x=y++ x=5 y=6 Decrement x= y x=4 y=4 x=y x=5 y=4 CMPT 165: Introduction to the Internet and the WWW: Java Script 19 CMPT 165: Introduction to the Internet and the WWW: Java Script 20

JavaScript Assignment Operators The + Operator Used on Strings Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators: Operator Example Same As Result = x=y x=5 x=5 += x+=y x=x+y x=15 -= x-=y x=x-y x=5 *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0 The + operator can also be used to add string variables or text values together. To add two or more string variables together, use the + operator. txt1="what a very"; txt2="nice day"; txt3=txt1 + " "+ txt2; After the execution of the statements above, the variable txt3 contains What a very nice day. Notice the placement of the space between the two strings using the quotes. CMPT 165: Introduction to the Internet and the WWW: Java Script 21 CMPT 165: Introduction to the Internet and the WWW: Java Script 22 Adding Strings and Numbers JavaScript Comparison and Logical Operators If you add a number and a string, the result will be a string. Example: x=5+5; //x is an integer, value is 10 x="5"+"5"; //x is a string, value is "55" x=5+"5"; //x is a string, value is "55" Comparison and Logical operators are used to test for true or false. Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example(s) == is equal to x==8 is false, x==5 is true === is exactly equal to (value and type) x===5 is true, x=== 5 is false!= is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document.write("too young"); CMPT 165: Introduction to the Internet and the WWW: Java Script 23 CMPT 165: Introduction to the Internet and the WWW: Java Script 24

Logical Operators Conditional Operator Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true or (x==5 y==5) is false! not!(x==y) is true JavaScript also contains a conditional operator that assigns a value to a variable based on some condition: variablename=(condition)?value1:value2 For example: greeting = (city=="sydney")?"hello from Sydney!":"Hello!"; If the variable city has the value of Sydney, then the variable greeting will be assigned the value Hello from Sydney! else it will be assigned Hello. CMPT 165: Introduction to the Internet and the WWW: Java Script 25 CMPT 165: Introduction to the Internet and the WWW: Java Script 26 JavaScript Conditional Statements If Statement Conditional statements are used to perform different actions based on different conditions. In JavaScript we have the following conditional statements: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false switch statement - use this statement to select one of many blocks of code to be executed Use the if statement to execute some code only if a specified condition is true. The syntax is: if (condition) code to be executed if condition is true Example: //Write a "Good morning" greeting if //the time is less than 10 var d=new Date(); var time=d.gethours(); if (time<10) document.write("<b>good morning</b>"); CMPT 165: Introduction to the Internet and the WWW: Java Script 27 CMPT 165: Introduction to the Internet and the WWW: Java Script 28

if...else statement if...else if...else statement Use the if...else statement to execute some code if a condition is true and another code if the condition is not true. The syntax is: if (condition) code to be executed if condition is true else code to be executed if condition is not true For example //If the time is less than 10, you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date(); var time = d.gethours(); if (time < 10) document.write("good morning!"); else document.write("good day!"); Use the if...else if...else statement to select one of several blocks of code to be executed. The syntax is: if (condition1) code to be executed if condition1 is true else if (condition2) code to be executed if condition2 is true else code to be executed if neither condition1 nor condition2 is true For example: var d = new Date() var time = d.gethours() if (time<10) document.write("<b>good morning</b>"); else if (time>=10 && time<16) document.write("<b>good day</b>"); else document.write("<b>hello World!</b>"); CMPT 165: Introduction to the Internet and the WWW: Java Script 29 CMPT 165: Introduction to the Internet and the WWW: Java Script 30 JavaScript Switch Statement Switch Example Use the switch statement to select one of many blocks of code to be executed. The syntax is: switch(n) case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 The variable (or expression) n is valuated once and its value is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. The word break is used to prevent the code from running into the next case automatically. //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); var theday=d.getday(); switch (theday) case 5: document.write("finally Friday"); break; case 6: document.write("super Saturday"); break; case 0: document.write("sleepy Sunday"); break; default: document.write("i m looking forward to this weekend!"); CMPT 165: Introduction to the Internet and the WWW: Java Script 31 CMPT 165: Introduction to the Internet and the WWW: Java Script 32

Popup Boxes Alert Box Confirm Box JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box. An Alert Box is often used to make sure information has reached the user. When it pops up, the user will have to click OK to proceed. alert("sometext"); function show_alert() alert("i am an alert box!"); <input type="button" onclick="show_alert()" value="show alert box" /> A confirm box is used if you want the user to verify or accept something. The syntax is: confirm("sometext"); When a confirm box pops up, the user will have to click either OK or Cancel to proceed. If the user clicks OK, the box returns true. If the user clicks Cancel, the box returns false. Example: function show_confirm() var r=confirm("press a button"); if (r==true) alert("you pressed OK!"); else alert("you pressed Cancel!"); <input type="button" onclick="show_confirm()" value="show confirm box" CMPT 165: Introduction to the Internet and the WWW: Java Script 33 CMPT 165: Introduction to the Internet and the WWW: Java Script 34 Prompt Box JavaScript Functions A prompt box is used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either OK or Cancel to proceed after entering an input value. If the user clicks OK the box returns the input value. If the user clicks Cancel the box returns null. The syntax is: prompt("sometext","defaultvalue"); Example: function show_prompt() var name=prompt("please enter your name","jane Doe"); if (name!=null && name!="") document.write("hello " + name + "!"); A function is a group of statements that are executed by a call to the function. To keep script from being executed by the browser when it loads a page, you can put it into a function. You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external.js file). Functions can be defined both in the and in the section of a document. To ensure that a function is loaded by the browser before it is called, define it in the section. <input type="button" onclick="show_prompt()" value="show prompt box" /> CMPT 165: Introduction to the Internet and the WWW: Java Script 35 CMPT 165: Introduction to the Internet and the WWW: Java Script 36

Defining a Function Function Example Use the following syntax to define a function: function functionname(var1,var2,...) some code The word function is a reserved word and used to define your function. The functionname is a word of your choosing, but should be relevant to the task your function will perform. The parameters var1, var2,... are variables or values passed into the function. The and the defines the start and end of the function, much as it did the declaration part of a CSS rule. A function with no parameters must still include (empty) parentheses after the function name. In the following script, the function displaymessage() is executed when the user clicks the input button. function displaymessage() alert("hello World!"); <form> <input type="button" value="click me!" onclick="displaymessage()"> </form> <p>by pressing the button above, a function will be called.</p> CMPT 165: Introduction to the Internet and the WWW: Java Script 37 CMPT 165: Introduction to the Internet and the WWW: Java Script 38 The return Statement Java Script Loops The return statement is used to specify the value that is returned from a function. Example: function product(a,b) return a*b; Loops execute a block of code a specified number of times, or while a specified condition is true. In JavaScript, there are two kind of loops: for: loops through a block of code a specified number of times while: loops through a block of code while a specified condition is true var x = 4; var y = 3; document.write("the product of " + x + " and " + CMPT 165: Introduction to the Internet and the WWW: Java Script 39 CMPT 165: Introduction to the Internet and the WWW: Java Script 40

The For Loop The While Loop The for loop is used when you know how many times the script should run. The syntax is: for (var=startvalue;var<=endvalue;var=var+increment) code to be executed Example: var i; for (i=0;i<=5;i++) document.write("the number is " + i); document.write("<br>"); The while loop loops through a block of code while a specified condition is true. while (variable<=endvalue) code to be executed The <= could be any comparison operator. The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: var i=0; while (i<=5) document.write("the number is " + i); document.write("<br>"); i++; CMPT 165: Introduction to the Internet and the WWW: Java Script 41 CMPT 165: Introduction to the Internet and the WWW: Java Script 42 The do...while Loop The do...while loop is a variant of the while loop. It will execute the block of code once, and then it will repeat the loop as long as the specified condition is true. do code to be executed while (variable<=endvalue); Example: var i=0; do document.write("the number is " + i); document.write("<br />"); i++; while (i<=5); CMPT 165: Introduction to the Internet and the WWW: Java Script 43