C ITS 1231 Web Tec hnolog ies. JavaScript: Document, Event, Date objects

Similar documents
Place User-Defined Functions in the HEAD Section

Full file at Tutorial 2: Working with Operators and Expressions

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

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

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

Javascript Lecture 23

CHAPTER 6 JAVASCRIPT PART 1

CITS1231 Web Technologies. JavaScript

Web Programming/Scripting: JavaScript

The first sample. What is JavaScript?

CGS 3066: Spring 2015 JavaScript Reference

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

Introduction to DHTML

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

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

Session 16. JavaScript Part 1. Reading

Working with JavaScript

Web Engineering (Lecture 06) JavaScript part 2

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

CS 110 Exam 2 Spring 2011

C HAPTER S EVEN F OCUS ON J AVAS CRIPT AND VBSCRIPT E XTENSIONS

IS 242 Web Application Development I

Q1. What is JavaScript?

Session 6. JavaScript Part 1. Reading

Client vs Server Scripting

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

Introduction to JavaScript

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

T his article is downloaded from

For loops and Window Objects:

COMS W3101: SCRIPTING LANGUAGES: JAVASCRIPT (FALL 2017)

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

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

JavaScript Introduction

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

COMS 469: Interactive Media II

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

INTRODUCTION TO JAVASCRIPT

CSC Web Programming. Introduction to JavaScript

JavaScript Introduction

Y oung W on Lim 9 /1 /1 7

JavaScript by Vetri. Creating a Programmable Web Page

Princess Nourah bint Abdulrahman University. Computer Sciences Department

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

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

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

Enhancing Web Pages with JavaScript

EVENT-DRIVEN PROGRAMMING

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

Unit Notes. ICAWEB411A Produce basic client-side script for dynamic web pages Topic 1 Introduction to JavaScript

JavaScript. What s wrong with JavaScript?

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

CISC 1600 Lecture 2.4 Introduction to JavaScript

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

Chapter 9: Simple JavaScript

A Balanced Introduction to Computer Science, 3/E

T his article is downloaded from

Task 1. Set up Coursework/Examination Weights

Such JavaScript Very Wow

Loops/Confirm Tutorial:

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

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

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

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

ORB Education Quality Teaching Resources

Programming language components

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

COMS 469: Interactive Media II

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

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

PIC 40A. Midterm 1 Review

IN Development in Platform Ecosystems Lecture 2: HTML, CSS, JavaScript

jquery Tutorial for Beginners: Nothing But the Goods

introjs.notebook March 02, 2014

Chapter 2 Working with Data Types and Operators

JavaScript. Learn to program using your browser

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

Lesson 1: Writing Your First JavaScript

Chapter 16. JavaScript 3: Functions Table of Contents

1. Cascading Style Sheet and JavaScript

CPA JS Tag. < Tracking Methodology and Examples > 2018/11/21

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Tutorial 10: Programming with JavaScript

CITS1231 Web Technologies

printf( Please enter another number: ); scanf( %d, &num2);

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

(Refer Slide Time: 01:40)

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

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

JavaScript s role on the Web

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

Project 2: After Image

A340 Laboratory Session #5

COMP519 Practical 5 JavaScript (1)

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

CSC Javascript

Like many institutions, University of Minnesota

People = End Users & Programmers. The Web Browser Application. Program Design Phase. Algorithm Design -Mathematical Y = MX + B

Transcription:

C ITS 1231 Web Tec hnolog ies JavaScript: Document, Event, Date objects

D oc um ent O bjec t JavaScript can interact with HTML page elements via the Document Object. The Document Object is accessed via the keyword document. Recall from previous lectures: document.writeln() to print out to page. Document Object has: Collections Properties Methods 2

D oc um ent M ethods w rite() Writes HTML or JavaScript to a document w riteln() Same as write(), but adds a newline character Note that newline characters are normally ignored by browser. You can use the <pre> tag to preserve line breaks. Example: <pre> document.writeln( Hello ); document.writeln( World ); document.write( Hello ); document.write( World ); </pre> 3

D oc um ent M ethods g ete lem entb yid() Accesses the first element with the specified id One can then access the various properties of this element innerhtml property refers to the text between the element s opening and closing tags 4 <head> <script type="text/javascript"> function getvalue() { var x=document.getelementbyid("myheader"); alert(x.innerhtml); } </script> </head> <body> <h1 id="myheader" onclick="getvalue()">click <em>me!</em></h1> </body> </html>

D oc um ent M ethods g ete lem ents B yn a m e() Accesses all elements with a specified name <head> <script type="text/javascript"> function calc() { var x=document.getelementsbyname("para"); alert("there are "+x.length+" paragraphs. First one says:"+x[0].innerhtml); } 5

D oc um ent M ethods g ete lem ents B yta g N a m e() Accesses all elements with a specified tagname <head> <script type="text/javascript"> function gettags() { var x=document.getelementsbytagname("input"); alert("there are "+x.length+" inputs. First second has value: "+x[1].value); } </script> </head> <body> <input type="text"/><br /> <input type="text"/><br /> <input type="text"/><br /> <input type="button" onclick="gettags()" value="how many input elements?" /> </body> </html> 6

U nders ta nding E vent H a ndlers Event Action that occurs within a Web browser Event handler Statement that tells browsers what code to run in response to specified event Syntax to insert event handler as an attribute <element onevent="script"...>... 7

Java S c ript E vent H a ndlers 8 Many more. See text or http://www.w3schools.com/jsref/dom_obj_event.asp

E vent: onkeydow n The user has pressed a key. Example: 9 <head> <script type="text/javascript"> function update(id) { var txt=document.getelementbyid(id).value; document.getelementbyid(id).value=txt.touppercase(); } </script> </head> <body> Type something: <input type="text" id="fname" onkeydown="update(this.id)" /> </body> </html> Why is the last character not uppercase? Character is not added to input text until key goes up. When key down, function is called to convert input text to upper case. Only when function returns and key is released, the last character is appended to input text (still lower case!).

E vent: onkeyup The user pressed a key and released it. Example: <head> <script type="text/javascript"> function update(id) { var txt=document.getelementbyid(id).value; document.getelementbyid(id).value=txt.touppercase(); } </script> </head> <body> Type something: <input type="text" id="fname" onkeyup="update(this.id)" /> </body> </html> Each character is made upper case on key going up. 10

E vent: onc ha ng e The content of the input field has changed. Example: <head> <script type="text/javascript"> function update(id) { var txt=document.getelementbyid(id).value; document.getelementbyid(id).value=txt.touppercase(); } </script> </head> <body> Type something: <input type="text" id="fname" onchange="update(this.id)" /> </body> </html> No change to characters as you type. Event onchange is triggered only when you hit Enter key. 11

E vent: onc lic k User has clicked mouse button. Example: <head> <script type="text/javascript"> function calc() { var num1 = parseint(document.getelementbyid('num1').value); document.getelementbyid('num2').value = num1*num1; } </script> </head> <body> Enter a number: <input type="text" id="num1" /> <button onclick="calc()">click to square it</button> <input type="text" id="num2" readonly="true" /> </body> </html> 12

D ate O bjec t Allows your JavaScript to work with dates and times. There are 4 ways to create a Date object: Date Object with current date and time: <body> <script type="text/javascript"> var dt=new Date(); document.write(dt); 13 </script>

D ate Initia lis e U s ing S tring variable = new Date("month day, year hours:minutes:seconds"); 14 <body> <script type="text/javascript"> var dt=new Date("June 1, 1977 10:11:00"); document.write(dt); </script> </body> </html>

D ate Initia lis ed U s ing N um ber var dt = new Date(num) num is number of ms past 01 Jan 01, 1970 00:00:00 UTC Perth is UTC+08:00:00 There are 86,400,000 ms in one day <body> <script type="text/javascript"> var dt=new Date(86400000); document.write(dt); </script> </body> </html> 15

D ate Initia lis ed U s ing S evera l Pa ra m eters new Date(yr, mth, day, hrs, mins, secs, ms) Parameters are numbers and optional. If you leave out a parameter, zero will be assumed and all subsequent parameters must be left out also. new Date(2010) is valid. new Date(2010,, 1) is invalid. <body> <script type="text/javascript"> var dt=new Date(2010,0,1,2); document.write(dt); </script> </body> </html> 16

E xtra c ting D ate a nd Tim e Va lues 17

S etting D ate a nd Tim e Va lues 18

C reating a C us tom D ate Func tion showd ate() function returns dd/mm/yyyy formatted date. <head> <script type="text/javascript"> function showd ate(dateobj) { var thisdate = dateobj.getdate(); //get day var this Month = dateobj.getmonth()+1; //get month (jan=0 s o add 1) var this Year = dateo bj.getfullyear(); return thismonth + "/" + thisdate + "/" + thisyear; //get year //format as dd/mm/yyyy } </script> 19 </head>

C reating a C us tom Tim e Func tion showtime() function returns hh:mm:ss formated time. <head> <script type="text/javascript"> function showtime(dateo bj) { thiss econd=dateo bj.gets econds(); var this Minute=dateO bj.getminutes(); var this Hour=dateO bj.gethours(); return thishour + ":" + thisminute + ":" + thiss econd; //get seconds //get minutes //get hours //format as hh:mm:ss } </script> 20 </head>

C a lc ulate D a ys to N ew Yea r calcd ays() function returns number days to new year. <head> <script type="text/javascript"> function calcd ays(dateo bj) { var nextyear=dateobj.getfullyear()+1; var newyear=new D ate(nextyear,0,1); var ms = newyear-dateobj; var days = ms /(1000*60*60*24); //get next year //create date of next new year //calc ms from now to new year //convert ms to days return days; } 21 </script> We want integer whole days. How to rid of decimals?

C a lc ulate D a ys to N ew Yea r C ont calcd ays() function returns number days to new year. <head> <script type="text/javascript"> function calcd ays(dateo bj) { var nextyear=dateobj.getfullyear()+1; var newyear=new D ate(nextyear,0,1); var ms = newyear-dateobj; var days = ms /(1000*60*60*24); //get next year //create date of next new year //calc ms from now to new year //convert ms to days return days; } 22 </script>

Tim e to N ew Yea r Time to New Year can be expressed in number of days, hours, minutes and seconds. calcdays() returns a number. Integer portion is number whole days to new year. Decimal portion can be converted to remainder hours, mins and secs. calchours() returns remainder hours calcmins() returns remainder minutes calcsecs() returns remainder seconds 23

c a lc H ours () rem a inder hours to N ew Yea r <head> <s cript type="text/javascript"> function calchours(days) { var fracd ay = days - Math.floor(days); var hours = fracday*24; // get fractional day // convert to hours return hours; 24 } </s cript> </head> <body> <pre>

c a lc M ins () rem a inder m inutes to N ew Yea r <head> <s cript type="text/javascript"> function calcmins(hours) { var frachours = hours - Math.floor(hours); var minutes = frachours*60; // get fractional hours // convert to minutes return minutes; 25 } </s cript> </head> <body> <pre>

c a lc S ec s () rem a inder s ec onds to N ew Yea r <head> <s cript type="text/javascript"> function calcs ecs(minutes) { var fracmins = minutes - Math.floor(minutes); var seconds = fracmins*60; // get fractional minutes // convert to seconds return s econds; 26 } </s cript> </head> <body> <pre>

A utom atic a lly U pdating C ountdow n Use JavaScript timing events id = settimeout("command", delay) execute code sometime in future cleartimeout(id) cancels settimeout() 27

s ettim eout E xa m ple <head> <script type="text/javascript"> var c=1000; function start() { document.getelementbyid('num').value=c; c--; settimeout("start()",1000); } </script> 28 </head>

C reating the monthname A rra y 29

C reating the writedaynames() Func tion 30

T he C om plete daysinmonth() Func tion 31

R unning Java S c ript C om m a nds a s Links Syntax <a href="javascript:script">content</a> The following code runs the calctotal() function <a href="javascript:calctotal()"> </a> C alculate total cost 32