Post on 14-Jan-2016
description
transcript
JavaScriptPart 1
Slide 2
Lecture Overview JavaScript background The purpose of JavaScript JavaScript syntax
Slide 3
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)
Slide 4
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
Slide 5
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
Slide 6
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
Slide 7
Creating a First Script <script> tag appears in a <head> or <body> tag
type argument denotes that it’s JavaScript
Example:
<script type=“text/javascript”>document.write(“hello”);
</script>
Slide 8
Creating a First Script
<html> <body>
<script type=“text/javascript">
document.write(“hello")
</script>
</body>
</html>
script tag
Script tag
Script language
Slide 9
Script Placement (1) A document may have multiple <script> blocks Scripts in a <head> block
Create procedures here Before or after the <style> section is fine
Scripts in a <body> block Code executes as the page is rendered
Importing external script files This is the recommended place to put
generic functions
Slide 10
Script Placement (2) Scripts appearing in a <head> tag but
outside a procedure execute first in the order they appear More about procedures later
Code in a procedure is not executed unless explicitly called
Scripts appearing in a <body> tag execute as they are encountered The placement has an effect on page
rendering
Slide 11
Handling Java Incapable Browsers
Include the <noscript> directive to display a message when JavaScript is disabled
<html> <body> <script language="javascript">
document.write("Greetings") </script> <noscript> <p>JavaScript is not enabled.</p> </noscript> </body></html>
Slide 12
JavaScript IS CASE SENSITIVE
Slide 13
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
Slide 14
Creating a First Script (Example) See JavaScriptExample1.htm
Pay particular attention to the order in which the script code executes
Slide 15
Comments Comments appear differently inside of
JavaScript block that outside of a JavaScript block
The characters // on a line mark the line as a comment
The strings /* and */ mark the begin and end of a multi-line comment
Slide 16
Adding Comments<html> <body>
<script language="javascript">
// This is a comment.
/* This is a two line
comment */
document.write("Greetings")
</script>
</body>
</html>
Slide 17
Variables (1) JavaScript is “loosely typed’ data types change dynamically as the
program runs Declare variables with the var
statement
Slide 18
Variables (2) Examples
var x // Now x is undefinedvar x = 5; // Now x is a Numbervar x = "John"; // Now x is a String
Slide 19
Variables (3) Like VB, there are local and global
variables Local variables are declared inside of a
procedure Global variables are declared in a <script> block but outside of a procedure
Slide 20
Functions (Introduction) They are the same thing as a VB
function or any other programming language function
Functions execute When called by another procedure When implemented as an event handler
Event handlers are discussed later
Slide 21
Declaring a Function function declarations typically appear
in the <head> section They are only executed when explicitly
called Syntax:
function name(parameter –list) {
statements:
}
Slide 22
Declaring a Function (Example) Declare a function named printMessage<head> <script type="text/javascript">function printMessage(msg){
alert(msg); } </script></head>
Slide 23
Calling a Function Functions execute when called
Call functions explicitly from other JavaScript code
Call functions implicitly from an event handler
Slide 24
Calling a Function (Exampple) From another function or from within
another JavaScript block, call the function with it’s name an parameters
Example:<script type="text/javascript"> printMessage();</script>
Slide 25
Returning a Value from a Function Call the return statement with an
argument as in
return 0;
Slide 26
Operators They are about the same as VB
% is the modulus operator though
http://www.w3schools.com/js/js_operators.asp
Slide 27
Comparisons Similar to VB
== is the test for equality != is the test for inequality
http://www.w3schools.com/js/js_comparisons.asp
Slide 28
Decision-Making Again, conceptually similar to VB
{} mark blocks instead of EndIf
http://www.w3schools.com/js/js_if_else.asp
Slide 29
Loops While VB we have for loops and while
loops
Slide 30
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
Slide 31
Common Events (1) Mouse Motion
mouseover – mouse enters the region of an element
mouseout – mouse leaves the region of an element
focus – an element becomes active blur – an element because inactive
http://www.w3schools.com/tags/ref_eventattributes.asp
Slide 32
Common Events (2) Document related events
load – document loads unload – fires just before the document is
unloaded Button related
click – user clocks a button (or other element)
submit
Slide 33
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
Slide 34
Inline Event Handler (Example) The alert dialog appears when the user
clicks the button<body> <input type="button" value="Click Me" onclick= "alert('you clicked me');" />
</body>
Slide 35
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:
<input id="btnShowEvent" type="button" value="Execute event handler" onclick="btnShowEventClick()" />
Slide 36
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
Slide 37
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."
Slide 38
What is the Dom (2)?
Slide 39
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
Slide 40
The Basic DOM Hierarchy
Slide 41
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
Slide 42
We will talk about navigator (the browser itself) window (a window in the browser) document (the currently loaded
document in the browser)
Slide 43
The write() and writeln() 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
Slide 44
Determining the Browser Use the navigator object to get info
about the browser appVersion 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
Slide 45
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
Slide 46
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
Slide 47
The window Object (Introduction) 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() creates a new browser
window
Slide 48
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
Slide 49
The window Object (Attributes 1) fullscreen - defines whether window
fills the desktop toolbar – enable or disable the toolbar menubar – enable or disable the menu
bar resizable – allow or disallow window
resizing
Slide 50
The window Object (Attributes 2) alwaysRaised – browser floats on top of
other windows regardless of whether it is active
height and width define the window size
scrollbars defines whether scroll bars appear when necessary
Unspecified attributes will have false values
Slide 51
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")
Slide 52
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
Slide 53
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
Slide 54
The window Object (Members 2) Display a prompt with a text entry field
window.prompt(“message”, “Default”)
Display a confirmation dialog if (window.confirm("Exit")) {
window.close() }
Display a messagewindow.alert("Error")
Slide 55
The window Object (History 1) history – used for history navigation
window.history.back()window.history.forward()
Go back to pages and forward 2 pageswindow.history.go(-2)window.history.go(2)
Slide 56
The window Object (History 2) The history object also support the
following properties: current – the URL of the current
document length – the number of URLs in the
history list next – the next URL in the history list previous – the previous URL in the history
list
Slide 57
The window Object (Status bar) There are two properties to manage the
status bar defaultStatus – this message always
appears status – this message appears only
temporarily such as when the mouse hovers over a button or link
Display a status bar messagewindow.status("appears in the status bar")
Slide 58
The document Object The object represents your running
HTML document We can
find elements change elements add and delete elements
Slide 59
The document Object (Finding Elements)
Method Description
document.getElementById() Find an element by element id
document.getElementsByTagName() Find elements by tag name
document.getElementsByClassName() Find elements by class name
Slide 60
The document Object (Changing Elements)
Method Description
element.innerHTML= Change the inner HTML of an element
element.attribute= Change the attribute of an HTML element
element.setAttribute(attribute,value) Change the attribute of an HTML element
element.style.property= Change the style of an HTML element
Slide 61
The document Object (Adding / Deleting Elements)
Method Description
document.createElement() Create an HTML element
document.removeChild() Remove an HTML element
document.appendChild() Add an HTML element
document.replaceChild() Replace an HTML element
document.write(text) Write into the HTML output stream
Slide 62
The document Object (A Canonical List) Refer to W3Schools http://
www.w3schools.com/js/js_htmldom_document.asp
Slide 63
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 method to get a
reference to the node The method applies to the document object
Slide 64
Referencing Elements by ID (Example) Get and change the text in the paragraph
named First<script type="text/javascript"> function ShowTree() { x=document.getElementById("First"); x.innerHTML = "Changed"; }
</script> The paragraph declaration<p id="First">Hello world!</p>
Slide 65
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
Slide 66
Getting Elements by Tag Name (Example) Collapse (hide) all paragraph elements
Slide 67
Getting Elements by Query Selector The querySelectorAll() method
selects objects (elements) based on a CSS query selector These are the same query selectors that
you have used before
Slide 68
Getting Elements by Query Selector Collapse all <p> tags in a <section>
Slide 69
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
Slide 70
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_event.asp
Slide 71
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
Slide 72
JavaScript Keyboard Events onKeyDown: keyboard key is pressed onKeyUp: keyboard key is released onKeyPressed: keyboard key is pressed
and released
http://localhost:49811/IS360/IS360JavaScriptEvents.html
Slide 73
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