Transcript CHAPTER 1

JavaScript Part 1

Lecture Overview    JavaScript background The purpose of JavaScript JavaScript syntax

History Lesson    JavaScript is NOT Java Started at Netscape in 1995 Microsoft released its own version 'JScript" in 1996  JavaScript is the default scripting language in .NET (VBScript has pretty much faded away)

What do we do with JavaScript?

 A starter list  Adds sizzle to pages (Animation)        Dynamic HTML (DHTML) Client side data entry validation Client side CGI Reduce the load on overburdened servers Process and manage cookies Some servers are beginning to support JavaScript AJAX to load parts of Web pages

What is JavaScript? (1)    It’s a programming language that ‘closely’ resembles Java Implementations   European Computer Manufacturers Association created ECMAScript to standardize different scripting versions See ECMA-262  I’ll try to conform There are others It’s a “C ish” language

What is JavaScript (2)  Most of what we do is access the object model supported by the underlying browser   The W3C defines the Document Object Model (DOM) Differences do exist between browsers   I will try, where possible, to point out these differences Most support the common ECMA standards though

Creating a First Script   

Creating a First Script

script tag Script language

Script tag

Script Placement (1)   A document may have multiple

JavaScript is not enabled.

JavaScript IS CASE SENSITIVE

JavaScript Semantics   Semicolons need not terminate statements although they do no harm  Unless two statements are placed on the same line Variables 

var

data type is generic   JavaScript is not strongly typed like Java  Type conversion happens on the fly Other types 

number

,

boolean

,

string

,

function

,

object

Creating a First Script (Example)  See

JavaScriptExample1.htm

 Pay particular attention to the order in which the script code executes

Comments    Comments appear differently inside of JavaScript block that outside of a JavaScript block The characters a comment

//

on a line mark the line as The strings

/*

and

*/

mark the begin and end of a multi-line comment

Adding Comments

Variables (1)    JavaScript is “loosely typed’ data types change dynamically as the program runs Declare variables with the

var

statement

Variables (2)  Examples

var x // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String

Variables (3)    Like VB, there are local and global variables Local variables are declared inside of a procedure Global variables are declared in a

Calling a Function  Functions execute when called  Call functions explicitly from other JavaScript code  Call functions implicitly from an event handler

Calling a Function (Exampple)  From another function or from within another JavaScript block, call the function with it’s name an parameters  Example:

Returning a Value from a Function  Call the

return

as in statement with an argument

return 0;

Operators  They are about the same as VB  % is the modulus operator though  http://www.w3schools.com/js/js_operators.asp

Comparisons  Similar to VB  == is the test for equality  != is the test for inequality  http://www.w3schools.com/js/js_comparisons.asp

Decision-Making  Again, conceptually similar to VB  {} mark blocks instead of EndIf  http://www.w3schools.com/js/js_if_else.asp

Loops  While VB we have

for

loops loops and

while

JavaScript Events (Introduction)  Conceptually, Java Script events work just like .NET (VB) events  They fire as a result of some user or other action  Code that executes in response to an event is called an event handler  The syntax and event names differ between VB and JavaScript

Common Events (1)  Mouse Motion  

mouseover

element

mouseout

element – mouse enters the region of an – mouse leaves the region of an 

focus

– an element becomes active 

blur

– an element because inactive  http://www.w3schools.com/tags/ref_eventattrib utes.asp

Common Events (2)   Document related events 

load

– document loads 

unload

unloaded – fires just before the document is Button related 

click

– user clocks a button (or other element) 

submit

Creating Event Handlers    There are two ways to create event handlers Inline event handlers have code in the event argument Create functions and wire them to the event

Inline Event Handler (Example)  The alert dialog appears when the user clicks the button

Calling a Function from an Event handler   Event handlers are functions with some special characteristics The following statement calls the procedure btnShowEventClick when the button is clicked:

The Document Object Model    There really is not that much to the JavaScript language itself  It’s just a subset of Java JavaScript uses the Document Object Model (DOM) objects to get at the browser and its windows  This is where the real power comes in Standard defined by W3C and European Computer Manufactures Association (ECMA) hence ECMAScript  I’ll introduce the DOM here and go into more detail later

What is the DOM (1)?

  The HTML DOM is a tree objects It permits access to the contents, structure, and style of an HTML 5 document    An XML document too The DOM can communicate with multiple browser instances It’s formally defined by the W3C  "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

What is the Dom (2)?

What is the DOM (3)?

 Use the DOM to     dynamically create new document elements move document elements and remove them too hide and make visible elements Change CSS styles

The Basic DOM Hierarchy

DOM Programming Model   It’s an object model and a programming interface HTML elements are considered objects    They have properties to store data They have methods that perform actions They respond to events

We will talk about   

navigator window

(the browser itself) (a window in the browser)

document

(the currently loaded document in the browser)

The

write() writeln()

and Methods     Both write their argument to the output stream (HTML document) Both apply to the

document

object  More in a moment

write()

does not write a terminating carriage return

writeln()

does write a carriage return

Determining the Browser  Use the

navigator

the browser 

appVersion

object to get info about gets the major version   Netscape  Microsoft Internet Explorer

appMinorVersion

gets the minor version    Supported by IE only

appPlatform

gets the OS version

cookieEnabled

gets cookie status

Determining the Browser (Example)

document.write(navigator.appName) document.write(navigator.appVersion) document.write(navigator.appMinorVersion) document.write(navigator.platform) document.write(navigator.cookieEnabled)

See

JavaScriptNavigatorExample.htm

The

window

object   The

window

object provides a reference to the open browser window Through the

window

object, you can   Reference the elements on the page through the DOM Create new windows and destroy them

The

window

(Introduction) Object     It’s the root of the IE object hierarchy It refers to the IE Browser windows The

document

property contains a reference to the open document  More about the

document

object in a moment

window.open()

window creates a new browser

window.open

(Semantics)   

window

– refers to the browser window We can also use the keyword

self window.open (url, name, features)

 

url

contains URI or file name Second argument contains the

name

of the window  Features allows browser window configuration  It’s a comma-separated list of

key=value

pairs

The

window

(Attributes 1) Object    

fullscreen

the desktop

toolbar menubar

– enable or disable the toolbar – enable or disable the menu bar

resizable

resizing - defines whether window fills – allow or disallow window

The

window

(Attributes 2) Object    

alwaysRaised

other windows regardless of whether it is active – browser floats on top of

height

and

width

define the window size

scrollbars

defines whether scroll bars appear when necessary Unspecified attributes will have false values

The window Object (Attributes – Example)  Create a blank Web page without a toolbar or a menu bar  Note attributes appear as a comma separated list   1 and yes are equivalent 0 and no are equivalent

newWindow = window.open("","foo", "toolbar=no,menubar=no") newWindow = window.open("","foo", "toolbar=no,menubar=no")

The

window

Object (Best practices)    Do not use to create those dreaded banner ads Do not use to trap the user by handling

onClose

and displaying the window again Do not hide the title bar

The

window

Object (Example)  Display a very annoying window that’s hard to get rid of

window1 = window.open("","Annoy", "height=300,width=300,titlebar=no") window1.document.write("Annoying")

See

JavaScriptWindowMaker.htm

The

window

(Members 2) Object  Display a prompt with a text entry field

window.prompt(“message”, “Default” )

 Display a confirmation dialog

if (window.confirm("Exit")) { window.close() }

 Display a message

window.alert("Error")

The

window

(History 1) Object  history – used for history navigation

window.history.back() window.history.forward()

 Go back to pages and forward 2 pages

window.history.go(-2) window.history.go(2)

The

window

(History 2) Object  The history object also support the following properties: 

current

– the URL of the current document   

length next

– the number of URLs in the history list – the next URL in the history list

previous

– the previous URL in the history list

The

window

(Status bar) Object     There are two properties to manage the status bar

defaultStatus

– this message always appears

status

such as when the mouse hovers over a button or link – this message appears only temporarily Display a status bar message

window.status("appears in the status bar")

The

document

Object   The object represents your running HTML document We can    find elements change elements add and delete elements

The

document

Object (Finding Elements) Method document.getElementById() document.getElementsByTagName() document.getElementsByClassName() Description Find an element by element id Find elements by tag name Find elements by class name

The

document

Object (Changing Elements) Method element .innerHTML= element .

attribute= element .setAttribute

(attribute,value) element .style.

property= Description Change the inner HTML of an element Change the attribute of an HTML element Change the attribute of an HTML element Change the style of an HTML element

The

document

Object (Adding / Deleting Elements) Method document.createElement() document.removeChild() document.appendChild() document.replaceChild() document.write( text ) Description Create an HTML element Remove an HTML element Add an HTML element Replace an HTML element Write into the HTML output stream

The

document

Object (A Canonical List)   Refer to W3Schools http://www.w3schools.com/js/js_htmldom_d ocument.asp

Referencing Elements by ID  Remember each HTML element has an

ID

attribute  This attribute is special – it’s the unique identifier for the node   It’s value should begin with a letter for compatibility with all browsers Use the

GetElementByID

reference to the node method to get a  The method applies to the

document

object

Referencing Elements by ID (Example)  Get and change the text in the paragraph named First

 The paragraph declaration

Hello world!

Getting Elements by Tag Name    getElementsByTagName gets a list (array) of elements having a particular tag name The length property of the array tells us how many item are in the array Each element can be references via an array subscript

Getting Elements by Tag Name (Example)  Collapse (hide) all paragraph elements

Getting Elements by Query Selector  The

querySelectorAll()

objects (elements) based on a CSS query selector method selects  These are the same query selectors that you have used before

Getting Elements by Query Selector  Collapse all

tags in a

Changing the value of an Attribute   You can change the value of an attribute by specifying the attribute name to an element Change the src attribute of an image

JavaScript Events     JavaScript has several events These operate similarly to Visual Basic events Events can be roughly categorized as  Mouse events   Keyboard events Form events The canonical list  http://www.w3schools.com/jsref/dom_obj_even t.asp

JavaScript Mouse Events      

onMouseDown

: User has pressed the mouse button but has not released it

onMouseUp

: User has released the mouse button

onClick

: User has pressed and released the mouse button

onMouseMove

: User has moved the mouse

onMouseOver

: Mouse has entered the region of a control

onMouseOut

: Mouse has left the region of a control

JavaScript Keyboard Events   

onKeyDown

: keyboard key is pressed

onKeyUp

: keyboard key is released

onKeyPressed

: keyboard key is pressed and released  http://localhost:49811/IS360/IS360JavaScript Events.html

JavaScript Form Events     

onBlur

: when an element loses focus

onFocus

: when an element gets focus

onInvalid

: when an element input is not valid

onReset

: when a form is reset

onSubmit

: when the form is submitted to the server