JavaScript Basics & HTML DOM. Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com



Similar documents
«W3Schools Home Next Chapter» JavaScript is THE scripting language of the Web.

JavaScript: Client-Side Scripting. Chapter 6

Web Development 1 A4 Project Description Web Architecture

c. Write a JavaScript statement to print out as an alert box the value of the third Radio button (whether or not selected) in the second form.

Dynamic Web-Enabled Data Collection

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

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 06 (Nebenfach)

Programming the Web 06CS73 SAMPLE QUESTIONS

JavaScript and Dreamweaver Examples

JavaScript Introduction

Client-side programming with JavaScript. Laura Farinetti Dipartimento di Automatica e Informatica Politecnico di Torino laura.farinetti@polito.

Client-side Web Engineering From HTML to AJAX

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

MASTERTAG DEVELOPER GUIDE

Technical University of Sofia Faculty of Computer Systems and Control. Web Programming. Lecture 4 JavaScript

Accessibility in e-learning. Accessible Content Authoring Practices

Yandex.Widgets Quick start

Web Hosting Prep Lab Homework #2 This week: Setup free web hosting for your project Pick domain name and check whether it is available Lots of free

LAB MANUAL CS (22): Web Technology

CSC309 Winter 2016 Lecture 3. Larry Zhang

FORM-ORIENTED DATA ENTRY

In order for the form to process and send correctly the follow objects must be in the form tag.

Script Handbook for Interactive Scientific Website Building

Web Programming Step by Step

Working with forms in PHP

Real SQL Programming 1

DOM, Jav Ja a v Script a and AJA AJ X A Madalina Croitoru IUT Mont Mon pellier

Short notes on webpage programming languages

Javascript for beginners

A Tale of the Weaknesses of Current Client-side XSS Filtering

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Intell-a-Keeper Reporting System Technical Programming Guide. Tracking your Bookings without going Nuts!

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs


Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 03 Major Subject

How to Create Dynamic HTML and Javascript using your Data Jennifer Sinodis, Bank One, Phoenix, AZ

WIRIS quizzes web services Getting started with PHP and Java

Mobile Web Applications. Gary Dubuque IT Research Architect Department of Revenue

Web application development (part 2) Netzprogrammierung (Algorithmen und Programmierung V)

Web design. FDC Workshop: WebPage Design. Agenda. All you wanted to know about designing your own personal webpage without daring ask about it!

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Slide.Show Quick Start Guide

JISIS and Web Technologies

This matches a date in the MM/DD/YYYY format in the years The date must include leading zeros.

IMRG Peermap API Documentation V 5.0

It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

Novell Identity Manager

Overview. In the beginning. Issues with Client Side Scripting What is JavaScript? Syntax and the Document Object Model Moving forward with JavaScript

Finding XSS in Real World

InPost UK Limited GeoWidget Integration Guide Version 1.1

AJAX The Future of Web Development?

2- Forms and JavaScript Course: Developing web- based applica<ons

Further web design: HTML forms

Creating a Guest Book Using WebObjects Builder

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

Introduction to XHTML. 2010, Robert K. Moniot 1

AJAX and JSON Lessons Learned. Jim Riecken, Senior Software Engineer, Blackboard Inc.

04 Links & Images. 1 The Anchor Tag. 1.1 Hyperlinks

COURSE SYLLABUS EDG 6931: Designing Integrated Media Environments 2 Educational Technology Program University of Florida

07 Forms. 1 About Forms. 2 The FORM Tag. 1.1 Form Handlers

Web Programming with XHTML

[ LiB ] [ LiB ] Learn JavaScript In a Weekend By Jerry Lee Ford, Jr. Publisher: Premier Press Pub Date: 2003 ISBN: X Pages: 472

Chapter 14: Links. Types of Links. 1 Chapter 14: Links

ANGULAR JS SOFTWARE ENGINEERING FOR WEB SERVICES HASAN FAIZAL K APRIL,2014

Internet Technologies

The Web Web page Links 16-3

Website Planning Checklist

CS412 Interactive Lab Creating a Simple Web Form

WIDAM - WEB INTERACTION DISPLAY AND MONITORING

Web Application Exploits

Government Girls Polytechnic, Bilaspur

Web Programming with PHP 5. The right tool for the right job.

PHP Tutorial From beginner to master

Online Multimedia Winter semester 2015/16

HTML Forms and CONTROLS

Client SuiteScript Developer s Guide

Nome database: reddito

A Tale of the Weaknesses of Current Client-Side XSS Filtering

DC60 JAVA AND WEB PROGRAMMING JUNE b. Explain the meaning of the following statement public static void main (string args [ ] )

Using Object- Oriented JavaScript

Lab 5 Introduction to Java Scripts

Developer Guide: Hybrid Apps. SAP Mobile Platform 2.3

Online Multimedia Winter semester 2015/16

People Data and the Web Forms and CGI. HTML forms. A user interface to CGI applications

Circulation. o Check Out receipts printed after a patron checks items out. o Check in receipts printed after items are checked in.

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

Modern browsers support many technologies beyond (X)HTML, CSS, and JavaScript.

Certified PHP Developer VS-1054

PLAYER DEVELOPER GUIDE

GSM Security Camera EYE-02 Publishing pictures from EYE-02 camera on your website

Portals and Hosted Files

Chapter 22 How to send and access other web sites

WEB Javascript 3 Credit Hours

Web Development and Core Java Lab Manual V th Semester

Interaction between web browsers and script engines

Advanced Layer Popup Manual DMXzone Advanced Layer Popup Manual

JavaScripts in HTML must be inserted between <script> and </ script> tags.

Hypercosm. Studio.

Dynamic Web Pages With The Embedded Web Server. The Digi-Geek s AJAX Workbook

Transcription:

JavaScript Basics & HTML DOM Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com

2 Disclaimer & Acknowledgments Even though Sang Shin is a full-time employee of Sun Microsystems, the contents here are created as his own personal endeavor and thus does not necessarily reflect any official stance of Sun Microsystems on any particular technology Acknowledgments > The contents of this presentation was created from JavaScript tutorial from www.w3cschools.com

3 Topics What is and Why JavaScript? How and Where do you place JavaScript code? JavaScript language JavaScript functions JavaScript events JavaScript objects JavaScript HTML DOM objects Closure (need to be added)

What is and Why JavaScript?

5 What is JavaScript? Was designed to add interactivity to HTML pages Is a scripting language (a scripting language is a lightweight programming language) JavaScript code is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

What can a JavaScript do? JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate input data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies 6

How and Where Do You Place JavaScript Code?

How to put a JavaScript code into an HTML page? Use the <script> tag (also use the type attribute to define the scripting language) <html> <head> <script type="text/javascript">... </script> </head> <body> <script type="text/javascript">... </script> </body> </html> 8

9 Where Do You Place Scripts? Scripts can be in the either <head> section or <body> section Convention is to place it in the <head> section <html> <head> <script type="text/javascript">... </script> </head>

Referencing External JavaScript File Scripts can be provided locally or remotely accessible JavaScript file using src attribute <html> <head> <script language="javascript" type="text/javascript" src="http://somesite/myownjavascript.js"> </script> <script language="javascript" type="text/javascript" src="myownsubdirectory/myown2ndjavascript.js"> </script> 10

JavaScript Language

JavaScript Variable You create a variable with or without the var statement var strname = some value strname = some value When you declare a variable within a function, the variable can only be accessed within that function If you declare a variable outside a function, all the functions on your page can access it The lifetime of these variables starts when they are declared, and ends when the page is closed 12

13 JavaScript Popup Boxes Alert box > User will have to click "OK" to proceed > alert("sometext") Confirm box > User will have to click either "OK" or "Cancel" to proceed > confirm("sometext") Prompt box > User will have to click either "OK" or "Cancel" to proceed after entering an input value > prompt("sometext","defaultvalue")

14 JavaScript Language Conditional statement > if, if.. else, switch Loop > for loop, while loop try...catch throw

JavaScript Functions (which behave like Java methods) More on Functions in other Presentation

JavaScript Funcitons A JavaScript function contains some code that will be executed only by an event or by a call to that function > To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external.js file). Functions can be defined either <head> or <body> section > As a convention, they are typically defined in the <head> section 16

Example: JavaScript Function <html> <head> <script type="text/javascript"> // If alert("hello world!!") below had not been written within a // function, it would have been executed as soon as the page gets loaded. function displaymessage() { alert("hello World!") } </script> </head> <body> <form> <input type="button" value="click me!" onclick="displaymessage()" > </form> </body> </html> 17

JavaScript Events

Events & Event Handlers Every element on a web page has certain events which can trigger invocation of event handlers Attributes are inserted into HTML tags to define events and event handlers 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 19

Events onabort - Loading of an image is interrupted onblur - An element loses focus onchange - The content of a field changes onclick - Mouse clicks an object ondblclick - Mouse double-clicks an object onerror - An error occurs when loading a document or an image onfocus - An element gets focus onkeydown - A keyboard key is pressed 20

21 Events onkeypress - A keyboard key is pressed or held down onkeyup - A keyboard key is released onload - A page or an image is finished loading onmousedown - A mouse button is pressed onmousemove - The mouse is moved onmouseout - The mouse is moved off an element onmouseover - The mouse is moved over an element onmouseup - A mouse button is released

22 Events onreset - The reset button is clicked onresize - A window or frame is resized onselect - Text is selected onsubmit - The submit button is clicked onunload - The user exits the page

23 onload & onunload Events 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 Both the onload and onunload events are also often used to deal with cookies that should be set when a user enters or leaves a page.

24 onfocus, onblur and onchange The onfocus, onblur and onchange events are often used in combination with validation of form fields. Example: The checkemail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkemail()">;

25 Example & Demo: onblur <html> <head> <script type="text/javascript"> function uppercase() { var x=document.getelementbyid("fname").value document.getelementbyid("fname").value=x.touppercase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="uppercase()"> </body> </html>

26 onsubmit The onsubmit event is used to validate all form fields before submitting it. Example: The checkform() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be canceled. The function checkform() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.html" onsubmit="return checkform()">

Example & Demo: onsubmit <html> <head> <script type="text/javascript"> function validate() { // return true or false based on validation logic } </script> </head> <body> <form action="tryjs_submitpage.htm" onsubmit="return 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> 27

28 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: <a href="http://www.w3schools.com" onmouseover="alert('an onmouseover event');return false"> <img src="w3schools.gif" width="100" height="30"> </a>

JavaScript Objects

JavaScript Object JavaScript is an Object Oriented Programming (OOP) language A JavaScript object has properties and methods > Example: String JavaScript object has length property and touppercase() method <script type="text/javascript"> var txt="hello World!" document.write(txt.length) document.write(txt.touppercase()) </script> 30

31 JavaScript Built-in Objects String Date Array Boolean Math

32 JavaScript Object vs. Java Object Simlarities > Both has properties and methods Differences > JavaScript object can be dynamically typed while Java object is statically typed > In JavaScript, properties and methods are dynamically added

JavaScript Objects; 3 Different Ways of Creating JavaScript Objects

34 Creating Your Own JavaScript Objects 3 different ways > Create a direct instance of an object by using built-in constructor for the Object class > Create a template (Constructor) first and then create an instance of an object from it > Create object instance as Hash Literal

Option 1: Creating a Direct Instance of a JavaScript Object By invoking the built-in constructor for the Object class personobj=new Object(); // Initially empty with no properties or methods Add properties to it personobj.firstname="john"; personobj.age=50; Add an anonymous function to the personobj personobj.tellyourage=function(){ alert( This age is + this.age); } // You can call then tellyourage function as following personobj.tellyourage(); 35

Option 1: Creating a Direct Instance of a JavaScript Object Add a pre-defined function function tellyourage(){ alert( The age is + this.age); } personobj.tellyourage=tellyourage; Note that the following two lines of code are doing completely different things // Set property with a function personobj.tellyourage=tellyourage; // Set property with returned value of the function personobj.tellyourage=tellyourage(); 36

37 Option 2: Creating a template of a JavaScript Object The template defines the structure of a JavaScript object in the form of a function You can think of the template as a constructor function Person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.tellyourage=function(){ alert( This age is + this.age); } }

38 Option 2: Creating a template of a JavaScript Object Once you have the template, you can create new instances of the object myfather=new Person("John","Doe",50,"blue"); mymother=new Person("Sally","Rally",48,"green"); You can add new properties and functions to new objects myfather.newfield = some data ; myfather.myfunction = function() { alert(this["fullname"] + is + this.age); }

Option 3: Creating JavaScript Object as a Hash Literal Create personobj JavaScript object var personobj = { firstname: "John", lastname: "Doe", age: 50, tellyourage: function () { alert( The age is + this.age ); } tellsomething: function(something) { alert(something); } } personobj.tellyourage(); personobj.tellsomething( Life is good! ); 39

JavaScript Objects: Hash (Associative Array)

JavaScript Object is an Associative Array (Hash) A JavaScript object is essentially an associative array (hash) with fields and methods, which are keyed by name { firstname: "John", lastname: "Doe", age: 50, tellyourage: function () { alert( The age is + this.age ); }, tellsomething: function(something) { alert(something); } } The following two lines of code are semantically equivalent myobject.myfield = something ; myobject['myfield'] = something ; 41

JavaScript Objects: Classes, Objects, Inheritance

JavaScript has No built-in concept of Inheritance JavaScript has a concept of objects and classes (like in Java) but no built-in concept of inheritance (unlike in Java) > Every JavaScript object is really an instance of the same base class, a class that is capable of binding member fields and functions to itself at runtime 43

JavaScript Objects: prototype

45 prototype A prototype is a property of every JavaScript object Functions and properties can be associated with a constructor's property When a function is invoked with new keyword, all properties and methods of the prototype for the function are attached to the resulting object

46 prototype // Constructor of the MyObject function MyObject(name, size){ this.name=name; this.size=size; } // Add a function to the prototype MyObject.prototype.tellSize=function{ alert( size of + this.name+ is + this.size); } // Create an instance of the object. The new object has tellsize() method. var myobj=new MyObject( Sang, 30 inches ); myobj.tellsize();

JavaScript Objects: Functions Again

48 A function is a first-class JavaScript Object Functions are a bit like Java methods > They have arguments and return values A function is a first-class object in JavaScript (unlike in Java) > Can be considered as a descendant of Object > Can do everything a regular JavaScript object can do such as storing properties by name > Function objects can have other function objects as methods

49 A function can take Variable arguments You can call myfunction() or myfunction(20) function myfunction(value){ if (value){ this.area=value; } return this.area; }

JavaScript Objects: Context

HTML DOM Objects

HTML DOM The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents All HTML elements, along with their containing text and attributes, can be accessed through the DOM. > The contents can be modified or deleted, and new elements can be created. The HTML DOM is platform and language independent > It can be used by any programming language like Java, JavaScript, and VBScript 52

53 HTML DOM Objects Anchor object Document object Event object Form and Form Input object Frame, Frameset, and IFrame objects Image object Location object Navigator object

54 HTML DOM Objects Option and Select objects Screen object Table, TableHeader, TableRow, TableData objects Window object

Document Object

56 Document Object: Write text to the output <html> <body> <script type="text/javascript"> document.write("hello World!") </script> </body> </html>

57 Document Object: Write text with Formatting to the output <html> <body> <script type="text/javascript"> document.write("<h1>hello World!</h1>") </script> </body> </html>

58 Document Object: Use getelementbyid() <html> <head> <script type="text/javascript"> function getelement() { var x=document.getelementbyid("myheader") alert("i am a " + x.tagname + " element") } </script> </head> <body> <h1 id="myheader" onclick="getelement()">click to see what element I am!</h1> </body> </html>

Document Object: Use getelementsbyname() <html> <head> <script type="text/javascript"> function getelements() { var x=document.getelementsbyname("myinput") alert(x.length + " elements!") } </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> 59

60 Document Object: Return the innerhtml of the first anchor in a document <html> <body> <a name="first">first anchor</a><br /> <a name="second">second anchor</a><br /> <a name="third">third anchor</a><br /> <br /> InnerHTML of the first anchor in this document: <script type="text/javascript"> document.write(document.anchors[0].innerhtml) </script> </body> </html>

Document Object: Access an item in a collection <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("form1").name + "</p>") </script> </body> 61

Event Object

63 Event Object: What are the coordinates of the cursor? <html> <head> <script type="text/javascript"> function show_coords(event) { x=event.clientx y=event.clienty alert("x coords: " + x + ", Y coords: " + y) } </script> </head> <body onmousedown="show_coords(event)"> <p>click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html>

64 Event Object: What is the unicode of the key pressed? <html> <head> <script type="text/javascript"> function whichbutton(event) { alert(event.keycode) } </script> </head> <body onkeyup="whichbutton(event)"> <p><b>note:</b> Make sure the right frame has focus when trying this example!</p> <p>press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p> </body> </html>

Event Object: Which element was clicked? <html> <head> <script type="text/javascript"> function whichelement(e) { var targ if (!e) var e = window.event if (e.target) targ = e.target else if (e.srcelement) targ = e.srcelement if (targ.nodetype == 3) // defeat Safari bug targ = targ.parentnode var tname tname=targ.tagname alert("you clicked on a " + tname + " element.") } </script> </head> <body onmousedown="whichelement(event)"> <p>click somewhere in the document. An alert box will alert the tag name of the element you clicked on.</p> <h3>this is a header</h3> <p>this is a paragraph</p> <img border="0" src="ball16.gif" width="29" height="28" alt="ball"> </body> 65

Event Object: Which event type occurred? <html> <head> <script type="text/javascript"> function whichtype(event) { alert(event.type) } </script> </head> <body onmousedown="whichtype(event)"> <p> Click on the document. An alert box will alert which type of event occurred. </p> </body> </html> 66

JavaScript Basics Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com