You are on page 1of 115

JavaScript

Web Engineering

1
Client-Side Programming
HTML is good for developing static pages
can specify text/image layout, presentation, links, …

Web page looks the same each time it is accessed

in order to develop interactive/reactive pages, must integrate programming in some form or
another
• client-side programming
 programs are written in a separate programming (or scripting) language
e.g., JavaScript, JScript, VBScript
 programs are embedded in the HTML of a Web page, with (HTML) tags to identify the
program component
e.g., <script type="text/javascript"> … </script>
 the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML
 could also allow the user (client) to input information and process it, might be used to
validate input before it’s submitted to a remote server
Scripts vs. Programs
a scripting language is a simple, interpreted programming language
scripts are embedded as plain text, interpreted by application

simpler execution model: don't need compiler or development environment


saves bandwidth: source code is downloaded, not compiled executable
platform-independence: code interpreted by any script-enabled browser
but: slower than compiled code, not as powerful/full-featured

JavaScript: the first Web scripting language, developed by Netscape in 1995


syntactic similarities to Java/C++, but simpler, more flexible in some respects,
limited in others
(loose typing, dynamic variables, simple objects)

JScript: Microsoft version of JavaScript, introduced in 1996


same core language, but some browser-specific differences
fortunately, IE, Netscape, Firefox, etc. can (mostly) handle both
JavaScript & JScript

JavaScript 1.5 & JScript 5.0 cores both conform to ECMAScript standard

VBScript: client-side scripting version of Microsoft Visual Basic


Common Scripting Tasks
adding dynamic features to Web pages
validation of form data (probably the most commonly used application)
image rollovers
time-sensitive or random page elements
handling cookies
Ajax adds ability to update page elements without (re)loading a webpage

defining programs with Web interfaces


utilize buttons, text boxes, clickable images, prompts, etc

• limitations of client-side scripting


 since script code is embedded in the page, it is viewable to the world
 for security reasons, scripts are limited in what they can do
e.g., can't access the client's hard drive
 since they are designed to run on any machine platform, scripts do not contain platform
specific commands
 script languages are not full-featured
e.g., JavaScript objects are very crude, not good for large project development
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)

5
What is JavaScript?
 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
JavaScript
JavaScript code can be embedded in a Web page using <script>
tags
document.write displays text in the page
 the output of JavaScript code is displayed as if directly entered in
<html>
text to be displayed can include HTML
HTML
<head>
tags
<title>JavaScript Page</title>
</head>
the tags are interpreted by the browser
<body> as normal when the text is displayed
<script type="text/javascript">

document.write("<p>Hello world!</p>"); as in C++/Java, statements end with ;


but a line break might also be interpreted as
document.write(" <p>How are <br/> " +
" <i>you</i>?</p> "); the end of a statement (depends upon
</script> browser)
<p>Here is some static text as well.</p>
JavaScript comments similar to C++/Java
</body>
</html> // starts a single line comment
/*…*/ enclose multi-line comments
Where to Place Scripts?
 Three places to define
 First: Place it within the head of the HTML document. Scripts here
aren't automatically executed when the page loads but can be referred
to by other scripts within the document.
 Second: Define a script within the body of the HTML document.
Scripts here are executed as the page loads.
 Third: Define a script within an event handler.

 Can also include the src attribute to the script tag


 Save script to an external file and include it in the HTML file.
 Use the .js extension when saving JavaScript to an external file.
     <script src="menu.js">
The above would include the JavaScript from the menu.js file.

8
Where to Place Scripts?
 Where to Put the JavaScript
 Scripts in the body section will be executed WHILE the page loads.
 Scripts in the head section will be executed when CALLED.

 Scripts in the head section:


 <html> <head> <script type="text/javascript"> some statements </script> </head>

 Scripts in the body section:


 <html> <head> </head> <body> <script type="text/javascript"> some statements </script>
</body>
 Scripts in both the body and the head section:
 <html> <head> <script type="text/javascript"> some statements </script> </head> <body>
<script type="text/javascript"> some statements </script> </body>

9
Example
 Put a JavaScript Into an HTML Page
 <html> <body> <script type="text/javascript"> document.write("Hello
World!") </script> </body> </html>
 The code above will produce this output on an HTML page:
Hello World!
 Explanation:
Use the <script> tag. Use the type attribute
 <script type="text/javascript">:

to define the scripting language


 document.write("Hello World!"): The JavaScript command for writing
some output to a page is document.write
 </script>: <script> tag has to be closed.

10
Defining Variables

11
JavaScript let

12
Defining Functions

13
Defining Functions

14
Defining Functions

15
Defining Functions

16
Defining Functions

17
Scope

18
Scope Chain

19
Scope Chain

20
Defining Variables, Function, and Scope

21
Example

22
Example

23
JavaScript Operators & Control Statements
standard C++/Java operators & control
<html> statements are provided in JavaScript
<head> • +, -, *, /, %, ++, --, …
<title>Folding Puzzle</title> • ==, !=, <, >, <=, >=
</head> • &&, ||, !,===,!==
<body> • if , if-else, switch
<script type="text/javascript">
var distanceToSun = 93.3e6*5280*12; • while, for, do-while, …
var thickness = .002;

var foldCount = 0; Suppose you took a piece of paper


thickness *= 2;
and folded it in half, then in half again,
foldCount++; and so on.
}
document.write("<p>Number of folds = " +
foldCount+"</p>"); How many folds before the thickness
</script> of the paper reaches from the earth to
</body>
</html> the sun?

*Lots of information is available online


JavaScript Math Routines
<html> the built-in Math
<!–- COMP519 js04.html 11.10.14 -->
object contains many
<head> functions and
<title>Random Dice Rolls</title> constants
</head>

<body> Math.sqrt
<div style="text-align:center"> Math.pow
<script type="text/javascript"> Math.abs
var roll1 = Math.floor(Math.random()*6) + 1;
var roll2 = Math.floor(Math.random()*6) + 1;
Math.max
Math.min
document.write("<img src='http://www.csc.liv.ac.uk/"+ Math.floor
"~martin/teaching/comp519/Images/die" + Math.ceil
roll1 + ".gif' alt='die showing " + roll1 + "'/>"); Math.round
document.write("&nbsp;&nbsp;");
document.write("<img src='http://www.csc.liv.ac.uk/"+
Math.PI
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif' alt='die showing " + roll2 + "'/>"); Math.E
</script>
</div> Math.random
</body> function returns a real
</html>
number in [0..1)
view page
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")

26
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");
 Display a message in a dialog box.
 The dialog box will block the browser.

var answer = confirm("Are you sure?");


 Display a message in a dialog box with two buttons: "OK" or
"Cancel".
 confirm() returns true if the user click "OK". Otherwise
it returns false.
prompt()
prompt("What is your student id number?");
prompt("What is your name?”, "No name");

 Display a message and allow the user to enter a value


 The second argument is the "default value" to be displayed in
the input textfield.
 Without the default value, "undefined" is shown in the input
textfield.

 If the user click the "OK" button, prompt() returns the value
in the input textfield as a string.
 If the user click the "Cancel" button, prompt() returns null.
JavaScript Language

Conditional statement
> if, if.. else, switch
 Loop
> for loop, while loop
 try...catch
 throw

All have the same syntax as those found in C


and Java.
30
JavaScript Functions
•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, write script as a function

•Function can be called 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 in <head> or <body> section


• As a convention, they are typically defined in the <head>
section

31
User-Defined Functions
function definitions are similar to C++/Java, except:
no return type is specified for the function (since variables are loosely typed)
no variable typing for parameters (since variables are loosely typed)
by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0 and is an integer Can limit variable scope to the function.
// Returns: true if n is prime, else false
{ if the first use of a variable is preceded
if (n < 2) {
return false; with var, then that variable is local to
} the function
else if (n == 2) {
return true;
}
for modularity, should make all
else { variables in a function local
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
33
Function Example
<html>

<head> Function definitions


<title>Prime Tester</title>
(usually) go in the
<script type="text/javascript">
function isPrime(n)
<head> section
// Assumes: n > 0
// Returns: true if n is prime <head> section is
{
// CODE AS SHOWN ON PREVIOUS SLIDE loaded first, so then
} the function is
</script> defined before code
</head>
in the <body> is
<body> <p> executed (and,
<script type="text/javascript">
testNum = parseFloat(prompt("Enter a positive integer", "7"));
therefore, the
function can be
if (isPrime(testNum)) { used later in the
document.write(testNum + " <b>is</b> a prime number."); body of the HTML
}
else { document)
document.write(testNum + " <b>is not</b> a prime number.");
}
</script> </p>
</body>
</html>
view page
35
Event-driven programming

36
you are used to programs that start with a main method
(or implicit main like in PHP)
JavaScript programs instead wait for user actions
called events and respond to them
event-driven programming: writing programs driven
by user events
Let's write a page with a clickable button that pops up
a "Hello, World" window...

37
38
Event handlers

39
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
• Mouse hovering over a hot spot on the web page
• Selecting an input box in an HTML form
• Submitting an HTML form
• A keystroke

40
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
 onkeypress - A keyboard key is pressed or held down
 onkeyup - A keyboard key is released

41
Events
 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
 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

42
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

43
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() ">;

44
45
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


46 checkForm()">
47
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) </a>

48
JavaScript Object
JavaScript is an Object Oriented Programming (OOP)
language.It supports programming with objects.

Objects are a way of organizing the variables.

 The different screen elements such as Web pages, forms,


text boxes, images, and buttons are treated as objects.

Objects are just data, with properties and methods

Properties are values associated with objects.


Methods are actions that objects can perform.
49
Objects - Properties and Methods

• Every object has its own properties and methods.

• Properties define the characteristics of an object.


Examples: color, length, name, height, width

• Methods are the actions that the object can perform or that
can be performed on the object.
Examples: alert, confirm, write, open, close

50
Naming Objects
• Objects are organized in a hierarchy.
• To refer to an object use :
objectName
• To refer to a property of an object use:
objectName.propertyName
• To refer to a method of an object use:
objectName.methodName()

JavaScript Built-in objects


String
Date
Array
Boolean
51 Math
Built in object -String
a String object encapsulates a sequence of characters, enclosed
in quotes

properties of a String include


 length : stores the number of characters in the string
methods include
 charAt(index) : returns the character stored at the given index
 (as in C++/Java, indices start at 0)
 substring(start, end) : returns the part of the string between the start
 (inclusive) and end (exclusive) indices
 toUpperCase() : returns copy of string with letters uppercase
 toLowerCase() : returns copy of string with letters lowercase

to create a String in JavaScript, assign using new keyword or (in the case of a String) just
make a direct assignment (new is implicit for a String assignment)
word = new String("foo"); word = "foo";

53 properties/methods are called exactly as in C++/Java


 word.length word.charAt(0)
String example: Palindromes
function strip(str) suppose we want to test
// Assumes: str is a string whether a word or phrase is
// Returns: str with all but letters removed
{
a palindrome
var copy = "";
for (var i = 0; i < str.length; i++) { noon Radar
if ((str.charAt(i) >= "A" && str.charAt(i) <= "Z") ||
(str.charAt(i) >= "a" && str.charAt(i) <= "z")) {
Madam, I'm Adam.
copy += str.charAt(i); A man, a plan, a canal:
} Panama!
}
return copy;
}
must strip non-letters out of the
function isPalindrome(str) word or phrase
// Assumes: str is a string
// Returns: true if str is a palindrome, else false
{
make all chars uppercase in
str = strip(str.toUpperCase()); order to be case-insensitive
for(var i = 0; i < Math.floor(str.length/2); i++) { finally, traverse and compare
if (str.charAt(i) != str.charAt(str.length-i-1)) {
return false; chars from each end
}
}
return true;
}54
<html>
<head>
<title>Palindrome Checker</title>

<script type="text/javascript">
function strip(str){
// CODE AS SHOWN ON PREVIOUS SLIDE
}

function isPalindrome(str){
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>

<body> <p>
<script type="text/javascript">
text = prompt("Enter a word or phrase", "Madam, I'm Adam");

if (isPalindrome(text)) {
document.write("'" + text + "' <b>is</b> a palindrome.");
}
else {
document.write("'" + text + "' <b>is not</b> a palindrome.");
}
</script> </p>
</body>
</html>
JavaScript Arrays
 Arrays store a sequence of items, accessible via an index
 Since JavaScript is loosely typed, elements do not have to be the same type
 To create an array, allocate space using new (or can assign an array directly using the
proper syntax shown below)
items = new Array(10); //allocates space for 10 items (but can grow)

items = new Array(); // if no size given, will adjust dynamically

items = [0,0,0,0,0,0,0,0,0,0]; // can assign size & values []

 To access an array element, use [] (as in C++/Java)


for (i = 0; i < 10; i++) {
items[i] = i; // initializes array with values 0, .., 9
}

 The length property stores the number of items in the array


for (i = 0; i < items.length; i++) {
document.write(items[i] + "<br/>"); // displays elements one line at
a
// time
}
Date Object
 Date object is used to access the date and time, and to perform "date
arithmetic"
 To create a Date object, use new & supply year/month/day/… as desired
today = new Date(); // sets to current date & time
newYear = new Date(2002,0,1);//sets to Jan 1,2002 12:00AM

 Methods include:
 newYear.getYear() can access individual components of a date
 newYear.getMonth()
 newYear.getDay()
 newYear.getHours()
 newYear.getMinutes()
 newYear.getSeconds()
 newYear.getMilliseconds()
Date Example
<html>
<head>
<title>Time page</title> by default, a date will be displayed in
</head> full, e.g.,
<body>
Time when page was loaded: Sun Feb 03 22:55:20 GMT-0600
<script type="text/javascript"> (Central Standard Time) 2002
now = new Date();
document.write("<p>" + now + "</p>");
time = "AM"; can pull out portions of the date using
hours = now.getHours();
if (hours > 12) { the methods and display as desired
hours -= 12;
time = "PM" here, determine if "AM" or "PM" and
} adjust so hour between 1-12
else if (hours == 0) {
hours = 12; 10:55:20 PM
}
document.write("<p>" + hours + ":" +
now.getMinutes()
+ ":" + now.getSeconds() + " " +
time + "</p>");
</script>
</body>
</html>
Another Date Example
<html>
<head>
<title>Time page</title> you can add and subtract Dates:
</head>
<body>
the result is a number of
<p>Elapsed time in this year: milliseconds
<script type="text/javascript">
now = new Date(); here, determine the number of
newYear = new Date(2014,0,1); seconds since New Year's day
secs = Math.round((now-newYear)/1000);
days = Math.floor(secs / 86400);
(note: January is month 0)
secs -= days*86400;
hours = Math.floor(secs / 3600); divide into number of days, hours,
secs -= hours*3600; minutes and seconds
minutes = Math.floor(secs / 60);
secs -= minutes*60
document.write(days + “days,”+hours+ “hours,”+
minutes +”minutes, and”+
secs + " seconds.");
</script>
</p>
</body>
</html>
Create Custom Objects
• With JavaScript you can define and create your own
objects. There are 2 different ways to create a new object:
• Define and create a direct instance of an object.
• Use a function to define an object, then create new object
instances.

60
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 a function to the personObj


personObj.tellYourage=function(){
alert(“This age is ” + this.age);
}/
/ You can call then tellYourage function as following
61 personObj.tellYourage();
Create objects using the Object function

Create a new object using the Object function, and add


a property and method.

var myObject = new Object();


myObject.myProp = "my prop value";
myObject.myMethod = function() {
  // Add custom JavaScript code here
}

62
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);
}
}
63 var obj= new Person();
function myObject() {
  this.myProp = "my prop value";
}
myObject.prototype.myMethod = function() {
  // Add custom JavaScript code here
}
 
var newObject = new myObject();

64
person.js job.js main.js
function Person(name, age, gender) function Job(title) { function main() {
{ this.title = title; var employee = new
this.age = age; this.description; Person("Richard", 23, male);
this.name = name; this.setDescription = document.getElementById("
this.gender = gender; function(description) mainBody").innerHTML =
this.job; { this.description = employee.getName(); }
this.setJob = function(job) {
description; } }
this.job = job; }
this.getAge = function() {
return this.age; }
this.getName = function() { <!DOCTYPE HTML>
return this.name; } <HTML>
<head> <title>javascript test</title>
this.getGender = function() {
<script src="person.js" type=“text/javascript"></script>
return this.gender; } } <script src="Job.js" type=“text/javascript"></script>
<script src="main.js" type=“tex/javascript"></script>
</head>
<body>
<p id="mainBody"></p>
65 </body>
</HTML>
The Browser Object Hierarchy

66
The Browser Objects (Global DOM)

67
The window object
the entire browser window (DOM top-level
object)
technically, all global code and variables
become part of the window object properties:
document, history, location, name

methods:
alert, confirm, prompt (popup boxes)
setInterval, setTimeoutclearInterval, clearTimeout (timers)
open, close (popping up new browser windows)
blur, focus, moveBy, moveTo, print, resizeBy, resizeTo,
scrollBy, scrollTo
68
Window object
<script>
<!DOCTYPE html>
var myWindow;
<html>
function openWin() {
<body>
myWindow = window.open("", "myWindow", "width=400,
<button onclick="openWin()">Open "myWindow"</button>
height=200");
}
<button onclick="closeWin()">Close "myWindow"</button>
function closeWin() {
<br><br>
if (myWindow) {
myWindow.close();
<button onclick="checkWin()">Has "myWindow" been
closed?</button> }}

<br><br> function checkWin() {


if (!myWindow) {
<div id="msg"></div> document.getElementById("msg").innerHTML =
"'myWindow' has never been opened!";
} else {
</body>
if (myWindow.closed) {
</html>
document.getElementById("msg").innerHTML =
"'myWindow' has been closed!";
} else
{ document.getElementById("msg").innerHTML =
"'myWindow' has not been closed!";
}
69
}}</script>
Window object

<!DOCTYPE html> <script>


<html> function goBack() {

<body> window.history.back();
}
</script>
<button onclick="goBack()">Go
Back</button>
</body>
</html>

70
Document Object Model

Document Object Model


Your web browser builds a model of the web
page (the document) that includes all the objects
in the page (tags, text, etc)
All of the properties, methods, and events
available to the web developer for manipulating
and creating web pages are organized into
objects
Those objects are accessible via scripting
languages in modern web browsers

71
HTML DOM Objects
• 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
72
This is what the browser reads

<html>
<head>
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.
</body>
</html>

This is what the browser displays on screen.


Document This is a drawing of the model that the
browser is working with for the page.
<html>

<head> <body>

<title>

"Sample DOM Document"


<h1> <p>

"An HTML Document"

"This is a" <i> "document"

"simple"
The HTML DOM Tree

75
Types of DOM nodes
<p>
This is a paragraph of text with a
<a href="/path/page.html">link in it</a>.
</p> HTML

element nodes (HTML tag)


can have children and/or attributes

text nodes (text in a block element)

attribute nodes (attribute/value pair)


text/attributes are children in an element node
cannot have children or attributes
76
not usually shown when drawing the DOM tree
Types of DOM nodes
<p>
This is a paragraph of text with a
<a href="/path/page.html">link in it</a>.
</p> HTML

77 CS380
HTML DOM
HTML DOM methods are actions you can perform (on HTML Elements)
add or deleting an HTML element

HTML DOM properties are values (of HTML Elements) that you can set or change
changing the content of an HTML element

html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html
Document Object: Write text to the
output

<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

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

80
Some information from a document

<html>
<head>
<title>DOM Sample 1</title>
</head>
<body>
Information about this document.<br>
<script type="text/javascript">
document.write("<br>Title: ",document.title);
document.write("<br>Referrer: ",document.referrer);
document.write("<br>Domain: ",document.domain);
document.write("<br>URL: ",document.URL);
</script>
</body>
</html>
Finding HTML Elements

82
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>
83
JavaScript function to get the values of First
and Last name of form. 
<!DOCTYPE html> function getFormvalue() {
<html>
var firstname =
<head>
(document.getElementsByName("
<title> fname"))[0].value;
Return first and last name from a form var secondname =
</title> (document.getElementsByName("
</head> lname"))[0].value;
<body> alert(firstname+ " " +
<form id="form1" onsubmit="getFormvalue()"> secondname);
First name: <input type="text" name="fname" }
value=“Ahmad"><br>
Last name: <input type="text" name="lname"
value=“Ali"><br>
<input type="submit" value="Submit">
</form> </body> </html>
84
Example
<html>
<body>

<p id="intro">Hello World!</p>


<p>This example demonstrates the <b>getElementById</b> method!</p>
<p id="demo"></p>

<script>
var myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script> Hello World!
</body> This example demonstrates the
</html> getElementById method!
The text from the intro paragraph is Hello
85 World!
JavaScript function to add rows to a table
<html> function insert_Row() {
<head> var x=
<title>Insert row in a table </title>
document.getElementById('sampleTable').insert
</head> Row(0);
<body>
<table id="sampleTable" border="1">
var y = x.insertCell(0);
<tr>
<td>Row1 cell1</td> var z = x.insertCell(1);
<td>Row1 cell2</td> y.innerHTML="New Cell1";
</tr> z.innerHTML="New Cell2"; }
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table><br>
<input type="button" onclick="insert_Row()"
86value="Insert row">
</body></html>
<html>
JavaScript: Remove items from a dropdown list
function removecolor()
<head> {
<style type="text/css">
var x=
body {margin: 30px;}
</style>
document.getElementById("colorSelect
<title>Remove items from a dropdown list
");
</title>
</head>
x.remove(x.selectedIndex);
<body> }
<form>
<select id="colorSelect">
<option>Red</option>
<option>Green</option>
<option>White</option>
<option>Black</option>
</select>
<input type="button" onclick="removecolor()"
value="Select and Remove">
</form>
87
</body>
getElementsByTagName()
getElementById() allows you to work with elements
by their individual id but often you will want to work
with a group of elements
getElementsByTagName() allows you to work with
groups of elements. This method returns an array

88
Example
<html>
<body>

<p>Hello World!</p>

<p>The DOM is very useful.</p>


<p>This example demonstrates the <b>getElementsByTagName</b> method</p>

<p id="demo"></p>

<script> Hello World!


var x = document.getElementsByTagName("p"); The DOM is very useful.
document.getElementById("demo").innerHTML = This example demonstrates the
'The first paragraph (index 0) is: ' + x[0].innerHTML; getElementsByTagName method
</script> The first paragraph (index 0) is: Hello
World!
</body>
89</html>
Document Object: Use
getElementsByName()
<html>
<head>
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("myInput")[0].value
Alert(“value of first element “+ x)
}
</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=“value of first input">
</body>
</html>
90
getElementsByClassName- Example
Hello World!
<html> The DOM is very useful.
<body> This example demonstrates the
getElementsByClassName method.
<p>Hello World!</p> The first paragraph (index 0) with class="intro": The
DOM is very useful.
<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>

<p id="demo"></p>

<script>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>

</body>
91
</html>
Finding HTML Objects

Property Description
document.anchors Returns all <a> elements that have a
name attribute
document.forms Returns all <form> elements
document.images Returns all <img> elements
document.title Returns the <title> element
document.URL Returns the complete URL of the
document

92
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>
93
</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>
94
</html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return
validateForm()" method="post">

First name: <input type="text" name="fname">

<input type="submit" value="Submit">


</form>
</body>
95
</html>
Example- anchors
<html>
<body>

<a name="html">HTML Tutorial</a><br>


<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of anchors are: " + document.anchors.length;
</script>

96 </body>
</html>
Changing HTML Elements

97
JavaScript HTML DOM - Changing CSS

 The HTML DOM allows JavaScript to change the style of HTML elements.
 Changing HTML Style
document.getElementById(id).style.property=new style

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color="blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>
98
Modify paragraph text style through javascript code using
button

<!DOCTYPE html>
function js_style() {
<html> //font styles added by JS:
<head> text.style.fontSize = "14pt";
<title>JS DOM paragraph style</title> text.style.fontFamily = "Comic Sans
</head> MS";
<body> text.style.color = "green"; }
<p id ='text'>JavaScript Exercises -
modify text style</p>
<div>
<button id="jsstyle”
onclick="js_style()">Style</button>
</div>
</body>
</html>

99
JavaScript HTML DOM Events

HTML DOM allows JavaScript to react to HTML events

<html>
<head>
<script>
function changetext(id){
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>

100
Creating new nodes

101
Modifying the DOM tree

102
Unobtrusive JavaScript

103
Unobtrusive JavaScript

104
Obtrusive event handlers (bad)

105
Attaching an event handler in JavaScript
code

106
When does my code run?

107
When does my code run?

108
A failed attempt to be unobtrusive

109
The window.onload event

110
An unobtrusive event handler

111
Anonymous functions

112
Anonymous function example

113
The keyword this

114
The keyword this

115
116

You might also like