JavaScript. Asst. Prof. Dr. Kanda Saikaew Dept. of Computer Engineering Khon Kaen University

Similar documents
The first sample. What is JavaScript?

Q1. What is JavaScript?

Introduction to JavaScript

JavaScript Introduction

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

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

Session 16. JavaScript Part 1. Reading

Session 6. JavaScript Part 1. Reading

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

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

Introduction to DHTML

Place User-Defined Functions in the HEAD Section

<form>. input elements. </form>

JavaScript s role on the Web

Events: another simple example

1$ 5 ! $ 6 4 * Source: 0 "!*! 0! * 8 97 ?!$ 5 0 *! 4! $ 0 : * ' () 7;7 7<7

Internet Technologies 5-Dynamic Web. F. Ricci 2010/2011

JavaScript Introduction

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall Project #1, Exam #1, old homework

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

Javascript. A key was pressed OR released. A key was released. A mouse button was pressed.

PES DEGREE COLLEGE BANGALORE SOUTH CAMPUS 1 K.M. before Electronic City, Bangalore WEB PROGRAMMING Solution Set II

Web Programming/Scripting: JavaScript

New Media Production Lecture 7 Javascript

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

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

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

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

Fundamentals of Website Development

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

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

Web Development & Design Foundations with HTML5

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

CSC Javascript

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

JAVASCRIPT HTML DOM. The HTML DOM Tree of Objects. JavaScript HTML DOM 1/14

CICS 515 a Internet Programming Week 3. Mike Feeley

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

DOM Primer Part 2. Contents

IS 242 Web Application Development I

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

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

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

JavaScript Handling Events Page 1

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

Chapter 16. JavaScript 3: Functions Table of Contents

CISC 1600 Lecture 2.4 Introduction to JavaScript

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

JavaScript Introduction

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

JAVASCRIPT. JavaScript is the programming language of HTML and the Web. JavaScript Java. JavaScript is interpreted by the browser.

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

Chapter4: HTML Table and Script page, HTML5 new forms. Asst. Prof. Dr. Supakit Nootyaskool Information Technology, KMITL

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

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

CHAPTER 6 JAVASCRIPT PART 1

COMP519 Web Programming Lecture 16: JavaScript (Part 7) Handouts

JavaScript Introduction

a.) All main headings should be italicized. h1 {font-style: italic;} Use an ordinary selector. HTML will need no alteration.

Web Development & Design Foundations with HTML5, 8 th Edition Instructor Materials Chapter 14 Test Bank

Javascript Lecture 23

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

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

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

INTRODUCTION TO WEB DEVELOPMENT AND HTML. Lecture 15: JavaScript loops, Objects, Events - Spring 2011

What Is JavaScript? A scripting language based on an object-orientated programming philosophy.

Princess Nourah bint Abdulrahman University. Computer Sciences Department

3Lesson 3: Functions, Methods and Events in JavaScript Objectives

A Balanced Introduction to Computer Science, 3/E

HTML User Interface Controls. Interactive HTML user interfaces. Document Object Model (DOM)

So don t copy files or photocopy - Share! Share these FREE Courses! End User License Agreement Use of this package is governed by the following terms:

JavaScript CSCI 201 Principles of Software Development

Netscape Introduction to the JavaScript Language

Introduction to JavaScript, Part 2

Share these FREE Courses!

Functions. INFO/CSE 100, Spring 2006 Fluency in Information Technology.

CSC 551: Web Programming. Spring 2004

JS Tutorial 3: InnerHTML Note: this part is in last week s tutorial as well, but will be included in this week s lab

COMS 469: Interactive Media II

1. Consider the following code snippet. Describe what the user will see when it is executed.

Loops/Confirm Tutorial:

Web Engineering (Lecture 06) JavaScript part 2

Want to add cool effects like rollovers and pop-up windows?

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

HTML and DHTML. Content. User Interaction Client-Side. Building ASP.NET Web Pages. Introduction. Web Applications Development with

Web Programming CS333/CS614

Client vs Server Scripting

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Chapter 8. Programming the Web. For the book Mapping in the Cloud Guilford Press Michael P. Peterson

The behavioural layer (JavaScript) Webpage Design

Client-side Techniques. Client-side Techniques HTML/XHTML. Static web pages, Interactive web page: without depending on interaction with a server

Introduction to using HTML to design webpages

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

Photo from DOM

Lesson 5: Introduction to Events

SEEM4570 System Design and Implementation Lecture 03 JavaScript

Software. Programming Languages. Types of Software. Types of Languages. Types of Programming. Software does something

Using JavaScript in a compatible way

Dynamic HTML becomes HTML5. HTML Forms and Server Processing. Form Submission to Web Server. DHTML - Mouse Events. CMST385: Slide Set 8: Forms

Practice problems. 1 Draw the output for the following code. 2. Draw the output for the following code.

Transcription:

JavaScript Asst. Prof. Dr. Kanda Saikaew (krunapon@kku.ac.th) Dept. of Computer Engineering Khon Kaen University 1

Why Learn JavaScript? JavaScript is used in millions of Web pages to Validate forms Detect browsers Create cookies JavaScript is the most popular scripting language on the internet, and works in all major browsers Internet Explorer 2 Mozilla Firefox

What is JavaScript? JavaScript was designed to add interactivity to HTML pages A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license 3

What Can a JavaScript Do? (1/3) JavaScript gives HTML designers a programming tool JavaScript is a scripting language with a very simple syntax! JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page 4

What Can a JavaScript Do? (2/3) JavaScript can react to events A JavaScript can be set to execute when something happens, like when a user clicks on an HTML element JavaScript can read and write HTML elements A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data A JavaScript can be used to validate form data before it is submitted to a server 5

What Can a JavaScript Do? (3/3) JavaScript can be used to detect the visitor's browser A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies A JavaScript can be used to store and retrieve information on the visitor's computer 6

How to Put a JavaScript into an HTML Page The HTML <script> tag is used to insert a JavaScript into an HTML page The word document.write is a standard JavaScript command for writing output to a page Syntax document.write( type what you want to write here ); 7

Example: js1.html <html> <body> <script type="text/javascript"> document.write("hello World!"); </script> </body> </html> 8

Where to Put the JavaScript (1/2) Scripts in the head section Scripts to be executed when they are called, or when an event is triggered, go in the head section When you place a script in the head section, you will ensure that the script is loaded before anyone uses it Example: <html> <head> <script type="text/javascript">... </script> </head> 9

Prompt Box Example Source code <html> <head> <script type="text/javascript"> var text = prompt("please enter text"); Output document.write("you have entered " + text); </head> </script> <body></body> </html> 10

Functions Source code <html> <head> <script type="text/javascript"> function displaymessage() { } </head> <body> </script> <form> alert("hello World!"); <input type="button" value="click me!" Output onclick="displaymessage()" > </form> </body> </html> 11

for...in Statement The for...in statement is used to loop (iterate) through the elements of an array or through the properties of an object. Syntax for (variable in object) { code to be executed } 12

for in Sample Source code <html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Toyota"; mycars[1] = "Volvo"; mycars[2] = "BMW"; Output for (x in mycars) { document.write("<b>" + mycars[x] + "</b><br />"); </html> </body> </script> } 13

Events By using JavaScript, we have the ability to create dynamic web pages Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions Events are normally used in combination with functions, and the function will not be executed before the event occurs! 14

Examples of Events A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke 15

onclick Sample Code Source code <html> <head> <script type="text/javascript"> var c=0; var t; function timedcount() { document.getelementbyid('txt').value=c; c=c+1; t=settimeout("timedcount()",1000); } </script> </head> Source code (cont.) <body> <form> <input type="button" value="start count!" onclick="timedcount()"> <input type="text" id="txt"> </form> <p>click on the button above. The input field will count for ever, starting at 0.</p> </body> </html> 16

onclick Sample Output settimeout ( expression, timeout ); where expression is the JavaScript code to run after timeout milliseconds have elapsed. 17

onload and onunload The onload and onunload events are triggered when the user enters or leaves the page The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information 18

onload Sample Source code <html> <head> <script type="text/javascript"> function detectbrowser() { var browser=navigator.appname; var b_version=navigator.appversion; var version=parsefloat(b_version); if ((browser=="netscape" browser=="microsoft Internet Explorer") && (version>=4)) { } } else { } alert("your browser is good enough!"); alert("it's time to upgrade your browser!"); </script></head> <body onload="detectbrowser()"/> </html> Output 19

onfocus, onblur and onchange The onfocus, onblur and onchange events are often used in combination with validation of form fields. Below is an example of how to use the onchange event. The checkemail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkemail()"> 20

onchange Sample Code <form name="go" onsubmit="return false;"> <select name="select" onchange="window.document.location=window.docume nt.go.select.value;"> <option value="#" selected>please Select</option> <option value="http://www.microsoft.com">microsoft</option> <option value="http://www.yahoo.com">yahoo!</option> <option value="http://www.google.com">google</option> </select> </form> 21

onchange Sample Output 22

onsubmit The onsubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onsubmit event <form method="post" action="xxx.htm" onsubmit="return checkform()"> The checkform() function will be called when the user clicks the submit button in the form If it returns true the form will be submitted, otherwise the submit will be cancelled 23

onmouseover and onmouseout onmouseover and onmouseout are often used to create "animated" buttons. Below is an example of an onmouseover event. An alert box appears when an onmouseover event is detected Example: <a href="http://www.w3schools.com" onmouseover="alert('an onmouseover event');return false"> <img src="w3schools.gif" width="100" height="30"> </a> 24

onmouseover and onmouseout Sample Source code <html> <head> <script type="text/javascript"> function mouseover() { document.b1.src ="b_blue.gif"; } function mouseout() { document.b1.src ="b_pink.gif"; } </script> </head> <body> <a href="http://gear.kku.ac.th" target="_blank"> <img border="0" alt="visit CoE KKU!" src="b_pink.gif" name="b1" width="26" height="26" onmouseover="mouseover()" onmouseout="mouseout()" /></a> </body> </html> Output 25

The try catch Statement The try catch statement allows you to test a block of code of errors The try block contains the code to be run The catch block contains the code to be executed if an error occurs Syntax try { // run some code here } catch (err) { // handle errors here } 26

The try catch Sample Code Source code <html> <head> <script type="text/javascript"> var txt="" function message() { try { } catch(err) { addalert("welcome guest!"); txt="there was an error on this page.\n\n"; txt+="click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { Source code (Cont.) </script> </head> <body> <input type="button" value="view message" onclick="message()" /> </body> </html> } } document.location.href="http://www. w3schools.com/"; } 27

The try catch Sample Output 28

The throw Statement The throw statement allows you to create an exception If you use this statement together with the try...catch statement You can control program flow and generate accurate error messages. Syntax throw(exception) The exception can be a string, integer, Boolean or an object Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error! 29

The throw Sample Code <html> <body> <script type="text/javascript"> var x=prompt("enter a number between 0 and 10:",""); try { if(x>10) throw "Err1"; else if(x<0) throw "Err2"; } catch(er){ if(er=="err1") alert("error! The value is too high"); else if(er == "Err2") alert("error! The value is too low"); } </script> </body> </html> 30

The throw Sample Output 31

JS Objects JavaScript is an Object Oriented Programming (OOP) language An OOP language allows you to define your own objects and make your own variable types. Note that an object is just a special kind of data An object has properties and methods 32

Object Properties Properties are the values associated with an object. Sample Code <script type="text/javascript"> var txt="hello World!"; document.write(txt.length); </script> The output of the code above will be: 12 33

Object Methods Methods are the actions that can be performed on objects. Sample code <script type="text/javascript"> var str="hello world!"; document.write(str.touppercase()); </script> The output of the code above will be: HELLO WORLD! 34

JS Date Object The Date object is used to work with dates and times. We define a Date object with the new keyword. The following code line defines a Date object called mydate: var mydate=new Date() The Date object will automatically hold the current date and time as its initial value! 35

JS Date: Date() Source code <html> <body> Output <script type="text/javascript" > document.write(date()); </script> </body> </html> 36

JS Date: gettime() Sample code <html> <body> <script type="text/javascript"> var minutes = 1000*60; var hours = minutes*60; var days = hours*24; var years = days*365; var d = new Date(); var t = d.gettime(); var y = t/years; document.write("it's been: " + y + " years since 1970/01/01!"); </script> </body> </html> Output 37

JS Date: setfullyear() Sample Code <html> <body> Output <script type="text/javascript"> var d = new Date(); d.setfullyear(1992,2,26); document.write(d); </script> </body> </html> 38

JS Date: getday() Sample Code <html> <body> <script type="text/javascript"> var d=new Date(); var weekday=new Array(7); weekday[0]="sunday"; weekday[1]="monday"; weekday[2]="tuesday"; weekday[3]="wednesday"; weekday[4]="thursday"; weekday[5]="friday"; weekday[6]="saturday"; document.write("today it is " + weekday[d.getday()]); </script> </body> </html> Output 39

JS Date: gethours, Source code <html> <head> <script type="text/javascript"> function starttime() { var today=new Date(); var h=today.gethours(); var m=today.getminutes(); var s=today.getseconds(); // add a zero in front of numbers<10 m=checktime(m); s=checktime(s); document.getelementbyid('txt').inner HTML=h+":"+m+":"+s; t=settimeout('starttime()',500); } Source code (Cont.) function checktime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="starttime()"> <div id="txt"></div> </body> </html> 40

JS Date: Output 41

JS Array: Create Array Sample Code <html> <body> <script type="text/javascript"> var mycars = new Array(); mycars[0] = "Toyota"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + "<br />"); } </script> </body> </html> Output 42

JS HTML DOM Document The Document object represents the entire HTML document It can be used to access all elements in a page. The Document object is part of the Window object and is accessed through the window.document property 43

Write Text to the Output Output Source code <html> <body> <script type="text/javascript"> document.write("hello World!"); </script> </body> </html> 44

Write Txt with Format to the Output Output Source code <html> <body> <script type="text/javascript"> document.write("<h1>this is a header</h1>"); </script> </body> </html> 45

Return the Title of a Document Output Source code <html> <head> <title>my title</title> </head> <body> The title of the document is: <script type="text/javascript"> document.write(document.title); </script> </body> </html> 46

Use getelementbyid (1/2) 47

Use getelementbyid (2/2) <html><head> <script type="text/javascript"> function getvalue() { } var x=document.getelementbyid("myheader"); alert(x.innerhtml); </script></head> <body> <h1 id="myheader" onclick="getvalue()">this is a header</h1> <p>click on the header to alert its value</p> </body> </html> 48

Use getelementsbyname (1/2) <html> <head> <script type="text/javascript"> function getelements() { var x=document.getelements ByName("myInput"); alert(x.length); } </script> </head> <body> <input name="myinput" type="text" size="20" /><br /> <input name="myinput" type="text" size="20" /><br /> <input name="myinput" type="text" size="20" /><br /> <br /> <input type="button" onclick="getelements()" value="how many elements named 'myinput'?" /> </body> </html> 49

Use getelementsbyname (2/2) 50

Access Form Name (1/2) <html> <body> <form id="form1" name="form1"> Your name: <input type="text"> </form> <form id="form2" name="form2"> Your car: <input type="text"> </form> <p> To access an item in a collection you can either use the number or the name of the item: </p> <script type="text/javascript"> document.write("<p>the first form's name is: " + document.forms[0].name + "</p>"); document.write("<p>the first form's name is: " + document.getelementbyid("fo rm1").name + "</p>"); </script> </body> </html> 51

Access Form Name (2/2) 52

Form Validation (1/6) Invalid Name 53

Form Validation (2/6) Invalid Age 54

Form Validation (3/6) Invalid Email 55

Form Validation (4/6) <html> <head> <script type="text/javascript"> function validate() { var at=document.getelementbyid("email").value.indexof("@"); var age=document.getelementbyid("age").value; var fname=document.getelementbyid("fname").value; submitok=true; if (fname.length>10) { alert("the name must be less than 10 characters"); submitok=false; } if (isnan(age) age<1 age>100) { alert("the age must be a number between 1 and 100"); submitok=false; } 56

Form Validation (5/6) if (at==-1) { alert("not a valid e-mail!"); submitok=false; } if (submitok) { document.write(""); window.location="http://localhost"; } } </script> </head> <body> 57

Form Validation (6/6) <form action="formvalidate.html" onsubmit="validate()"> Name (max 10 chararcters): <input type="text" id="fname" size="20"><br /> Age (from 1 to 100): <input type="text" id="age" size="20"><br /> E-mail: <input type="text" id="email" size="20"><br /> <br /> <input type="submit" value="submit"> </form> </body> </html> 58

References W3Schools, JavaScript Tutorial, available at http://www.w3schools.com/js/default. asp 59