Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

Web Engineering Javascript (Part 2) : Muhammad Umair Naru Department of Computer Science

This document provides an introduction to JavaScript concepts including window controls, event handlers, the Document Object Model (DOM), cookies, and more. It covers built-in properties and functions of the window and document objects, form objects, event handlers, manipulating the DOM tree, and creating time delays. The document is presented as part of a lecture on JavaScript with examples and explanations of core JavaScript topics.

Uploaded by

Naveed Shah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Web Engineering Javascript (Part 2) : Muhammad Umair Naru Department of Computer Science

This document provides an introduction to JavaScript concepts including window controls, event handlers, the Document Object Model (DOM), cookies, and more. It covers built-in properties and functions of the window and document objects, form objects, event handlers, manipulating the DOM tree, and creating time delays. The document is presented as part of a lecture on JavaScript with examples and explanations of core JavaScript topics.

Uploaded by

Naveed Shah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

Web Engineering

JavaScript (Part 2)
Muhammad Umair Naru
Department of Computer Science
Now we get into the cool stuff

• Now we get into the cool stuff


• The real power of JavaScript
– Window Controls
– Event Handlers
– DOM
– Cookies And much much more…

08/25/20 Introduction to Javascript 2


Window -Built-in Properties
• We have already seen the ‘document’ object –
how we print to screen

• ‘window’ object – JavaScript representation of a


browser window.
– closed -A boolean value that indicates whether the
window is closed.
– defaultStatus -This is the default message that is
loaded into the status bar when the window loads.
window.defaultStatus = “This is the status bar”;

08/25/20 Introduction to Javascript 3


Window – Built-in Functions
• alert("message")
• window.close()
• confirm("message")
• focus()
• open("URLname","Windowname",["options"])
– height, weight, alwaysRaised, location, menubar,
etc..
– open(“http://google.com”, “My
Google”,“toolbar=no,alwaysRaised=yes”);
08/25/20 Introduction to Javascript 4
Browser – Built-in Objects
• window.location
– href represents a complete URL.
– hostname represents the concatenation host:port.
– window.location.href=“http://google.com”;

• window.history
– length reflects the number of entries in the history list
– history.go(-1)
– history.back()
08/25/20 Introduction to Javascript 5
Form Object
• Form objects can be accessed by:
– window.document.myForm OR
window.document.forms[0]
• Properties
– action, target, length, method, etc…
• Functions
– window.document.myForm.submit();
– window.document.myForm.reset();
• Accessing Form Field Values
– window.document.myForm.firstname.value

08/25/20 Introduction to Javascript 6


(D)HTML Object Hierarchy

08/25/20 Introduction to Javascript 7


Event Handlers
• Events are actions that occur usually as a
result of something the user does. For
example, clicking a button is an event, as is
changing a text field or moving the mouse
over a hyperlink.
• Eg: Click, change, focus, load, mouseover,
mouseout, reset, submit, select

08/25/20 Introduction to Javascript 8


Event Handlers
• You can use event handlers, such as onChange
and onClick, to make your script react to
events.
– <input type=“button”
onClick=“javascript:doButton()>
– <select onChange=“javascript:doChange()”>
– <a onClick=“javascript:doSomething()”> </a>
– <form onSubmit=“javascript:validate()”>
– <body onLoad=“javascript:init()”>

08/25/20 Introduction to Javascript 9


DOM – Document Object Model
• W3C DOM, “The DOM”, DOM Level (1/2/3)
• Method of accessing / modifying XML
information on the page
• Tree structure of all HTML elements, including
attributes and the text theycontain.
• Contents can be modified or deleted
• New elements can be created and inserted into
the DOM Tree
• The concept is used in other languages, such as
Java (google: Java DOM)

08/25/20 Introduction to Javascript 10


DOM Representation of HTML

08/25/20 Introduction to Javascript 11


Document Object
• The document object is the JavaScript
interface to the DOM of any HTML page.
• Accessing elements:
– By name
document.getElementsByTagName(‘td')[indexOfColumn]
– By ID
document.getElementById('id')
– Walk the DOM Tree
document.childNodes[0].childNodes[1].childNodes[4]
08/25/20 Introduction to Javascript 12
Creating Time Delays
• Waits a specified amount of time, then calls a
function.
window.setTimeout('myFunc()',timeInMilliseconds);
• Waits a specified amount of time, then calls a
function. Then after the initial delay, the function
is called again
var myinterval =
window.setInterval('myFunc()',timeInMilliseconds);
– Wait / Call cycle is repeated until ‘clearInterval’ is
called window.clearInterval(myinterval);

08/25/20 Introduction to Javascript 13


Overview
• JavaScript in a Nutshell
• Basics
• Program structure
• Debugging
• JavaScript Objects
– Custom & Pre-built
– Window
– Document
• JavaScript and the HTML DOM
JavaScript in a Nutshell
JavaScript Conceptually

HTML Document
Code is written as a function
Header with which may in turn act on
Javascript code element
Body with
Elements

Text Box
Document element requests
function activation for a given
action – onclick
What Javascript Is and Is Not
• JavaScript is
– an interpreted loosely-typed object-based(?)
language
– event driven, embedded into HTML, and
dependent upon a simplified DOM
– still evolving and far from platform independent
• JavaScript is not
– simplified Java -- the two languages have
disjoint sets of capabilities
– simple -- mastery of JavaScript requires
advanced programming skills
What JavaScript Can and Can’t Do
• JavaScript can:
– Control document appearance and content,
including images
– Control the browser & interact with the user
– Establish network connections
– Read and write client state with cookies
• JavaScript can’t:
– Read or write files on the client
– Read or write files on the server without help
from a server-side script
– Support any kind of multithreading
JavaScript Basics
JavaScript Syntax
• Like Java, JavaScript…
– Is case-sensitive
– Ignores whitespace between “tokens”
– Uses C++ style (i.e. //) & C – style (i.e. /* */) comments
– Method and variable names must begin with a letter or _
• Unlike Java, Javascript…
– Semi-colons are optional.
– JavaScript is an untyped language
– Does not support data hiding (private, public, or protected)
– Variable declaration “var” is only required for “local” variables inside a
function when the same variable is used as a “global” variable.
Data Types
• Primitive Data Types
– Integer, Float, String, Boolean (true/false only)
– Functions are code that may be executed multiple times
– Objects are named pieces of data that have a collection of
properties
– Arrays are indexed collection of data values
– Null indicates “no value”
– Undefined returned when a variable doesn’t exist
• JavaScript does allow you to create your own
“classes” (more on this later.)
More on Strings
• A series of characters enclosed in single or
double quotes.
s = “Hello, ” + “world”; // Hello, world

• JavaScript has many built-in string operations.


– length() last_char= s.char(s.length -1);
– substring() sub = s.substring(0,4);
– indexOf() i = s.indexOf(‘a’);
– charAt() i = s.charAt(s.length-1);
Conditional Statements
if(name == null) name = “John Doe”

if((address == null) || (address == ““))


{
alert(“Please provide a mailing address”);
} else {
doSomething(address);
}
Loop Statements
while(count < 10) {
document.write(count);
count++; }

for (count=0; count<10; count++) {


document.write(count); }

// Object arrays
for (prop in myObject) {
document.write(“name: “ + prop ”; value: “ +
myObject[prop], “<br>“); }
Client-Side Program Structure
Client-Side Program Structure
• It is preferable to put JavaScript in an external file.
<script type="text/javascript” src="valid.js” />

• Technique for embedding JavaScript code in HTML:


<script language = “Javascript”>….</SCRIPT>

• A single HTML file may contain more than one pair of (non-
overlapping) <SCRIPT> tag pairs.
– JavaScript statement tags are executed in the order they appear.
– Javascript functions are executed when invoked

• Context scope is the HTML page, not the script block


– Different scripts on the same page are part of the same program.
– Be careful with variable and function names!
JavaScript and Namespaces
• Namespaces ensure that elements and
attributes are uniquely identified.
– XML: xmlns
– Java: packages (e.g., java.lang)
• JavaScript has no support for namespaces
– Possible naming collisions with third-party script
libraries or browser add-ons.
– Solution: define your set of functions within a
“local” variable.
JavaScript “Namespace” Example
// Use a name that is unique
var is2955 = {
affiliation: “University of Pittsburgh”,
title: “Unknown”,

setTitle: function(t) {
this.title = t;
}
};

// Later, we use our new object…


is2955.setTitle(“Web Engineering”);
document.write(is2955.title + “, “ + is2955.affiliation);
Debugging JavaScript
• Internet Explorer
– Errors will produce a dialog window with the error.
– Go to Internet Options/Advanced dialog to turn on
debugging.
• Mozilla (JavaScript Console)
– Tools / Error Console
– Type “javascript:” in the location textbox
• Excellent & free debugging plug-ins (e.g.,
FireBug) are available for Firefox.
JavaScript and Security
• JavaScript’s security model is based upon
Java’s for applets.
– Theoretically, downloaded scripts run in a
“sandbox” isolated from the OS.
– There is no File object or file access functions
(other than current document)
– No access to memory space or networking layer.
• Main problems deal with privacy
JavaScript and Security
• Same-origin policy
– Prevents scripts loaded from one site to get or set
properties in a document loaded form elsewhere.
– Same-origin check: document in target window &
document with calling script must have been
downloaded from the same server, using the
same protocol and port.
– Also applies to frames.
JavaScript
Objects and Events
Custom JavaScript Objects
• You may want to create your own objects:
– To build up a custom library
– To override pre-built objects and/or methods
• 2 steps to creating an object:
– Declare the new object as a function.
– Instantiate an instance with the “new” keyword.

var myUser = new User (“jpg14”);


myUser.setUserName();
Example: Custom Object Class
// Constructor
function User(userID) {
//define the object’s properties
this.affiliation = “University of Pittsburgh”,
this.id = userID;
this.name = “”;

//define the object’s methods


this.setName = setUserName;
}

function setUserName( ) {
var n = document.getElementById(“firstName”).value;
return n;
}
Pre-built Objects
browser

window navigator

location history document

anchor link image form


The Window Object
• Useful Window properties
– closed, length, name, opener, parent, self, status
• Useful Window methods
– alert(string),
– confirm(string),
– prompt(string, input default);
– open (arguments) opens a new window
• Useful Window events
– onBlur, onFocus
– onLoad, onUnload, onError
The Document Object
• Useful Document object properties
– cookie, lastModified, title
– domain, referrer, URL
• Useful Document object methods
– open() - opens document for writing
– write() and writeln()
<SCRIPT>
parent.frames[0].document.open();
parent.frames[0].document.write
(“<HR>Hello from your sibling frame!<HR>”);
parent.frames[0].document.close();
</SCRIPT>
Two Little Scripts using Document
Properties
• The document property “lastModified” is a date-time
string that specifies the last modification
< SCRIPT >
var theDate = “”;
theDate = document.lastModified;
document.write("This document was last modified ");
document.writeln(theDate);
</ SCRIPT >
• The referrer is the URL of the document that contained
the link that brought the user here
<SCRIPT>
if (document.referrer != null)
{document.write(“Glad to see you came from: ");
document.writeln(document.referrer);}
</SCRIPT>
JavaScript and the HTML DOM
An HTML Document Visually
<html>

<head> <body>

<title>
<a> <p>

text
Attr: href text text
Document Object Model
• DOM Level 1
– Allows access to & manipulation of all HTML
elements
– Supported by virtually all browsers.
• DOM Level 2
– Adds style sheet object model
– Adds an event model
• DOM Level 3
– Mainly for XML - Adds content model (DTD &
Schemas) and validation
DOM Nodes
• EVERYTHING in an HTML document is a node,
including the document itself.
– Elements
– Attributes
– Text
– Comments
• All nodes can be referred to directly or in
relation to one another (parent, child, sibling,
etc.)
Accessing Nodes
• Standard methods (read, cross-browser
compatible) for accessing DOM nodes:
– getElementById(id) : returns a node
– getElementsByTagName(tag): returns an array of
nodes.
– parentNode, firstChild, lastChild, previousSibling,
nextSibling
– Root Nodes
• document.documentElement
• document.body
Accessing Nodes (continued)
• Methods and properties for accessing a
collection of nodes:
– hasChildNodes() : does the node have children?
– childNodes[x] : a nodeList of children
• window.document.childNodes[0].childNodes[1]
– attributes: a collection of a node’s attributes.
• getAttribute(attr);
• hasAttribute(attr);
• setAttribute(attr, value);
• removeAttribute(attr);
Accessing Node Information
• We can get the name, value, and type for any
node:
– nodeName : tag name, attr name, #text, #document
– nodeValue : (attribute & text nodes only) value of
attribute or inner text of text node.
– nodeType : returns a number
• Element = 1
• Attribute = 2
• Text = 3
• Comment = 8
Creating Nodes
• We can create nodes and add them to our DOM
document:
– createElement(tag) : create a new HTML element
– createTextNode(‘string’)
– appendChild(new_node)

var newPara = document.createElement('p');


var newParaText = document.createTextNode('Some
content.');
newPara.appendChild(newParaText);
document.getElementById('someElementId').appendChild(newP
ara);
Fun with innerHTML
• An alternative to text nodes is manipulating
text through the innerHTML property:
– It’s innerHTML, NOT innerHtml!
– Originally meant for changing the text of an
anchor, but can be used with other tags.
• innerHTML Behavior
– myDiv.innerHTML = blah //replaces text
– myDiv.innerHTML += blah //appends text
Fun with HTML Tables
• Methods and properties exist solely for
manipulating tables, but browser support is
not very dependable.
• Best to use the previous methods, with one
caveat for <tbody>.
– Whether you explicitly use it or not, every table
has at least one <tbody>.
– Good practice: myTable.tbodies[0].whatever
HTML DOM and Events
• Starting with HTML 4.0, you can use HTML to trigger
events in the browser.
– Mouse clicks & movement
– Key presses
– Cursor position
• Some built-in events: onclick, onchange, onblur,
onfocus, onload, onunload;
• setTimeout(function, timeInMillis); // run once
• setInterval(function, timeInMillis); // loop
• addEventListener: create custom event and attach to
HTML element

You might also like