[go: up one dir, main page]

0% found this document useful (0 votes)
6 views59 pages

WS Lec7 Xxxxxxxxxx& HTML 3

This lecture introduces JavaScript as a client-side scripting language used to enhance web pages' interactivity and functionality. It covers the basics of JavaScript, including how to include scripts in HTML, obtaining user input through prompt dialogs, and using variables and operators. The document also explains the importance of event-driven programming and how to manipulate the Document Object Model (DOM) with JavaScript.

Uploaded by

ariraghad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views59 pages

WS Lec7 Xxxxxxxxxx& HTML 3

This lecture introduces JavaScript as a client-side scripting language used to enhance web pages' interactivity and functionality. It covers the basics of JavaScript, including how to include scripts in HTML, obtaining user input through prompt dialogs, and using variables and operators. The document also explains the importance of event-driven programming and how to manipulate the Document Object Model (DOM) with JavaScript.

Uploaded by

ariraghad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Web Systems - 502315-3

JavaScript & HTML


Lecture 7

Dr. Afnan Bukhari


Department of Information Technology

Original slides are prepared by:


Dr. Abdullah Baqasah
Contents
1. Introduction
2. First Script
3. Obtaining User Input with
prompt Dialogs
4. JavaScript and DOM
5. Events
6. Events and Event Handlers
7. Back to the DOM
Web Systems [502315-3] Dr. Afnan Bukhari 2
1. Introduction
Introduction

● In this lecture, we begin our introduction to the JavaScript scripting language,


which is used to enhance the functionality and appearance of web pages.
● JavaScript—is a de facto standard client-side scripting language for web-based
applications due to its highly portable nature.
● JavaScript serves two purposes:
1. It introduces client-side scripting, which makes web pages more dynamic
and interactive.
2. It provides the programming foundation for the server-side scripting.

Web Systems [502315-3] Dr. Afnan Bukhari 4


What is Javascript?

● A lightweight programming language ("scripting language") used


to make web pages interactive
● Insert dynamic text into HTML (ex: user name)
● React to events (ex: page load user click)
● Get information about a user's computer (ex: browser type)
● Perform calculations on user's computer (ex: form validation)
● A web standard (but not supported identically by all browsers)
● NOT related to Java other than by name and some syntactic
similarities

Web Systems [502315-3] Dr. Afnan Bukhari


Client-Side Scripting

Web Systems [502315-3] Dr. Afnan Bukhari


Why use client-side programming?

PHP already allows us to create dynamic web pages. Why also


use client-side scripting?

● Client-side scripting (JavaScript) benefits:


○ Usability: can modify a page without having to post
back to the server (faster UI)
○ Efficiency: can make small, quick changes to page
without waiting for server
○ Event-driven: can respond to user actions like clicks
and key presses

Web Systems [502315-3] Dr. Afnan Bukhari


Event-driven programming

Web Systems [502315-3] Dr. Afnan Bukhari


Using JavaScript in a browser

● JavaScript code is included within <script> tags:


○ <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
● Notes:
○ The type attribute is to allow you to use other scripting languages
(but JavaScript is the default)
○ This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document
○ The semicolon at the end of the JavaScript statement is optional but
preferred

Web Systems [502315-3] Dr. Afnan Bukhari


Where to put JavaScript

● JavaScript can be put in the <head> or in the <body> of an HTML document


○ JavaScript functions should be defined in the <head>
■ This ensures that the function is loaded before it is needed
○ JavaScript in the <body> will be executed as the page loads
● JavaScript functions can be put in a separate .js file
○ <script src="myJavaScriptFile.js"></script>
○ Put this in the <head>
○ An external .js file lets you use the same JavaScript on multiple HTML
pages
○ The external .js file cannot itself contain a <script> tag
● JavaScript can be put in an HTML form object, such as a button
○ This JavaScript will be executed when the form object is used

Web Systems [502315-3] Dr. Afnan Bukhari


JavaScript isn’t always available

● Some old browsers do not recognize script tags


○ These browsers will ignore the script tags but will display the included JavaScript
○ To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
○ The <!-- introduces an HTML comment
○ To get JavaScript to ignore the HTML close comment, -->, the // starts a
JavaScript comment, which extends to the end of the line
● Some users turn off JavaScript
○ Use the <noscript> message </noscript> to display a message in place of whatever
the JavaScript would put there

Web Systems [502315-3] Dr. Afnan Bukhari


2. First Script
First Script
1 <!DOCTYPE html>
● We begin with a simple script 2
(or program) that displays 3 <!-- Fig. 6.1: welcome.html -->
4 <!-- Displaying a line of text. -->
the text "Welcome to 5 <html>
JavaScript Programming!" 6 <head>
7 <meta charset = "utf-8">
in the HTML5 document (Fig, 8 <title>A First Program in JavaScript</title>
6.1) 9 <script type = "text/javascript">
11 document.writeln(
12 "<h1>Welcome to JavaScript Programming!</h1>" );
14 </script>
15 </head><body></body>
16 </html>

Web Systems [502315-3] Dr. Afnan Bukhari 13


First Script (cont.)

● Line 6 starts the <head> section of the document.


● JavaScript code will appear in the <head> section.
● The browser interprets the contents of the <head> section first, so the JavaScript
programs execute before the <body> of the HTML5 document displays.
● Later, we illustrate inline scripting, in which JavaScript code is written in the
<body> of an HTML5 document.

The script Element


● <script> tag indicate that the text which follows is part of a script.
● The type attribute specifies the MIME type of the script as well as the scripting
language, in our example, a text file written in javascript.

Web Systems [502315-3] Dr. Afnan Bukhari 14


First Script (cont.)

Strings
● Lines 11–12 instruct the browser’s JavaScript interpreter to perform an action,
namely, to display in the web page the string of characters contained between
the double quotation (") marks.
● Consecutive spaces appear in a string will be interpreted as single space.

Using the document Object


● Lines 11–12 use the browser’s document object, which represents the HTML5
document the browser is currently displaying.
● The browser creates a set of objects that allow you to access and manipulate
every element of an HTML5 document.

Web Systems [502315-3] Dr. Afnan Bukhari 15


First Script (cont.)

● The term object normally implies that attributes (data) and behaviors
(methods) are associated with the object.
● The object’s methods use the attributes to perform useful actions for the client
of the object.
● In lines 11–12, we call the document object’s writeln method to write a line of
HTML5 markup in the HTML5 document.
Statements
● Every statement in JavaScript ends with semicolon (;).
● Line 14 indicates the end of the script.

Note: JavaScript code is typically placed in a separate file, then included in the
HTML5 document that uses the script. This makes the code more reusable, because
it can be included into any HTML5 document.
Web Systems [502315-3] Dr. Afnan Bukhari 16
First Script (cont.)

Modifying First Script

Displaying Text in an Alert Dialog


● Sometimes it’s useful to display information in windows called dialogs (or dialog boxes) that
“pop up” on the screen to grab the user’s attention.
● Dialogs typically display important messages to users browsing the web page.
● The script in Fig. 6.3 displays Welcome to JavaScript Programming! As three lines in a
predefined dialog called an alert dialog.

Web Systems [502315-3] Dr. Afnan Bukhari 17


First Script (cont.)
1 <!DOCTYPE html>
Modifying First Script 2
3 <!-- Fig. 6.3: welcome3.html -->
4 <!-- Alert dialog displaying multiple lines. -->
The window Object 5 <html>
● Line 11 in the script uses the 6 <head>
browser’s window object to display 7 <meta charset = "utf-8">
8 <title>Printing Multiple Lines in a Dialog Box</title>
an alert dialog. 9 <script type = "text/javascript">
● The argument to the window 10 <!--
object’s alert method is the string 11 window.alert( "Welcome to\nJavaScript\nProgramming!" );
to display. 12 // -->
13 </script>
● The dialog provides an OK button ...
that allows the user to dismiss (i.e., 18 </html>
close) the dialog by clicking the
button.

Web Systems [502315-3] Dr. Afnan Bukhari 18


3. Obtaining User Input
with prompt Dialogs
Variables

● Variables can be declared with a var statement:


○ var pi = 3.1416, x, y, name = "Dr. Dave" ;
○ Variables names must begin with a letter or underscore
○ Variable names are case-sensitive
○ Variables are untyped (they can hold values of any type)

Identifiers
● The name of a variable can be any valid identifier.
● An identifier is a series of characters consisting of letters, digits, underscores ( _ ) and
dollar signs ($) that does not begin with a digit and is not a reserved JavaScript keyword.
● Identifiers may not contain spaces.

Web Systems [502315-3] Dr. Afnan Bukhari


Variables (cont.)

Some valid identifiers:


○ Welcome
○ $value
○ _value
○ m_inputField1
○ button7
Some invalid identifiers:
○ 7button (because it begins with a digit)
○ input field (because it contains a space)

Case Sensitivity
● JavaScript is case sensitive—uppercase and lowercase letters are considered to
be different characters, so name, Name and NAME are different identifiers.
Web Systems [502315-3] Dr. Afnan Bukhari 21
JavaScript Comments

JavaScript Comments
● In line 11, a single-line comment that begins with the characters //
states the purpose of the variable in the script.
● Comments do not cause the browser to perform any action when the
script is interpreted; rather, comments are ignored by the JavaScript
interpreter.

Multiline Comments
● You can also write multiline comments. For example,
/* This is a multiline
comment. It can be
split over many lines. */
is a multiline comment spread over several lines.

Web Systems [502315-3] Dr. Afnan Bukhari


Obtaining User Input with prompt Dialogs

● A script can adapt the content based on input from the user or other variables,
such as the time of day or the type of browser used by the client.
● Such web pages are said to be dynamic, as opposed to static, since their content
has the ability to change.

Dynamic Welcome Page


● Our next script creates a dynamic welcome page that obtains the user’s name,
then displays it on the page.
● The script uses another predefined dialog box from the window object—a prompt
dialog—which allows the user to enter a value that the script can use.

Web Systems [502315-3] Dr. Afnan Bukhari 23


Obtaining User Input with prompt Dialogs (cont.)
1 <!DOCTYPE html>
2
3 <!-- Fig. 6.5: welcome4.html -->
4 <!-- Prompt box used on a welcome screen -->
5 <html>
6 <head>
7 <meta charset = "utf-8">
8 <title>Using Prompt and Alert Boxes</title>
9 <script type = "text/javascript">
10 <!--
11 var name; // string entered by the user
12
13 // read the name from the prompt box as a string
14 name = window.prompt( "Please enter your name" );
15
16 document.writeln( "<h1>Hello " + name +
17 ", welcome to JavaScript programming!</h1>" );
18 // -->
19 </script>
20 </head><body></body>
21 </html>

Web Systems [502315-3] Dr. Afnan Bukhari 24


Obtaining User Input with prompt Dialogs (cont.)

String Concatenation
● Lines 16–17 use document.writeln to display the new welcome message.
● The expression inside the parentheses uses the operator + to “add” a string
("<h1>Hello, "), the variable name and another string (", welcome to
JavaScript programming!</h1>").
● JavaScript has a version of the + operator for string concatenation that enables
a string and a value of another data type (including another string) to be
combined.

● As you’ll see later, the + operator used for string concatenation can convert other
variable types to strings if necessary. Because string concatenation occurs
between two strings, JavaScript must convert other variable types to strings
before it can proceed with the operation.
Web Systems [502315-3] Dr. Afnan Bukhari 25
Operators & Statments

Familiar loop statements:


● Arithmetic Operators: while (condition) statement;
+, -, *, /, % do statement while (condition);
● Comparison Operators: for (initialization; condition; increment) statement;
< <= == != >= >
The switch statement:
● Logical Operators:
&&, ||, ! switch (expression) {
● String operator: + case label :
statement;
● If statements: break;
if (condition) statement; case label :
if (condition) statement; else statement; statement;
break;
...
default : statement;
}
Web Systems [502315-3] Dr. Afnan Bukhari
Obtaining User Input with prompt Dialogs (cont.)
1 <!DOCTYPE html> 20 // read in second number from user as a string
2 21 secondNumber = window.prompt( "Enter second integer"
3 <!-- Fig. 6.7: addition.html --> );
4 <!-- Addition script. --> 22
5 <html> 23 // convert numbers from strings to integers
6 <head> 24 number1 = parseInt( firstNumber );
7 <meta charset = "utf-8"> 25 number2 = parseInt( secondNumber );
8 <title>An Addition Program</title> 26
9 <script type = "text/javascript"> 27 sum = number1 + number2; // add the numbers
10 <!-- 28
11 var firstNumber; // first string entered by user 29 // display the results
12 var secondNumber; // second string entered by user 30 document.writeln( "<h1>The sum is " + sum + "</h1>" );
13 var number1; // first number to add 31 // -->
14 var number2; // second number to add 32 </script>
15 var sum; // sum of number1 and number2 33 </head><body></body>
16 34 </html>
17 // read in first number from user as a string
18 firstNumber = window.prompt( "Enter first integer" );
19

Web Systems [502315-3] Dr. Afnan Bukhari 27


Obtaining User Input with prompt Dialogs (cont.)

Web Systems [502315-3] Dr. Afnan Bukhari 28


Obtaining User Input with prompt Dialogs (cont.)

Adding Integers
● Our next script illustrates another use of prompt dialogs to obtain input from the
user. Figure 6.7 inputs two integers (whole numbers, such as 7, –11, 0 and 31914)
typed by a user at the keyboard, computes the sum of the values and displays the
result.
● Lines 11–15 declare the variables firstNumber, secondNumber, number1, number2
and sum.
● The script assigns the first value entered by the user to the variable firstNumber.
● Line 21 displays a prompt dialog to obtain the second number to add and assigns
this value to the variable secondNumber.
● Lines 24–25 convert the two strings input by the user to integer values that can be
used in a calculation. Function parseInt converts its string argument to an integer.

Web Systems [502315-3] Dr. Afnan Bukhari 29


Obtaining User Input with prompt Dialogs (cont.)

Data Types in JavaScript


● Unlike its predecessor languages C, C++ and Java, JavaScript does not require
variables to have a declared type before they can be used in a script.
● A variable in JavaScript can contain a value of any data type, and in many situations,
JavaScript automatically converts between values of different types for you.
● For this reason, JavaScript is referred to as a loosely typed language.
● When a variable is declared in JavaScript, but is not given a value, the variable has
an undefined value.
● Primitive Types: String, Number, Boolean, Undefined, Null.
● Reference Types: Objects, Arrays, Functions.

Web Systems [502315-3] Dr. Afnan Bukhari 30


Functions

● Functions should be defined in the <head> of an HTML page, to ensure that


they are loaded first
● One syntax for defining a function is:
function name (arg1, …, argN) { statements }
○ The function may contain return value; statements
○ Any variables declared within the function are local to it
● The syntax for calling a function is just
name(arg1, …, argN)
● Simple parameters are passed by value, objects are passed by reference
Web Systems [502315-3] Dr. Afnan Bukhari
Functions (cont.)
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>JavaScript Function Example</title>
6. </head>
7. <body>
8. <h2>JavaScript Function: Add Two Numbers</h2>
9. <p id="output" style="color: red;"></p>

10. <script>
11. // Function definition
12. function addNumbers(a, b) {
13. return a + b;
14. }

15. // Function call


16. var result = addNumbers(3, 3);

17. // Display result in the paragraph with id "output"


18. document.getElementById("output").textContent = "The sum is: " +
result;

19. </script>
20. </body>
21. </html>

Web Systems [502315-3] Dr. Afnan Bukhari


4. JavaScript and DOM
JavaScript and DOM

● JavaScript relies on a Document Object Model (DOM) that describes


the structure of the web page.

● You can do a lot with a just a little understanding of the DOM


○ You use the DOM to access elements on the web page
○ You can capture events without knowing the DOM at all
○ You need the DOM to make any changes to the web page

Web Systems [502315-3] Dr. Afnan Bukhari 34


JavaScript and DOM (cont.)

● JavaScript can change all the HTML elements


in the page.
● JavaScript can change all the HTML attributes
in the page.
● JavaScript can change all the CSS styles in
the page.
● JavaScript can remove existing HTML
elements and attributes.
● JavaScript can add new HTML elements and
attributes.
● JavaScript can react to all existing HTML
events in the page.
● JavaScript can create new HTML events in
the page.

Web Systems [502315-3] Dr. Afnan Bukhari


DOM Methods to Access Data

● Often, with JavaScript, you want to manipulate HTML elements.


● To do so, you have to find the elements first. There are several ways to do this:
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections

● Use the JavaScript getElementById("id") method.


● In practice, every item (like input boxes, textboxes, etc) should be given both a
name and an id (except for forms in the Strict XHTML).
● You can use also getElementByName("name"),
getElementsByTagName(”tagName");

Web Systems [502315-3] Dr. Afnan Bukhari 36


DOM Methods to Access Data (cont.)
Example of Using getElementById
<html><head> <title> Fun with Text Boxes </title> <body>
<style> .error { color:red; } </style> <form id="BoxForm" action="">
<script type="text/javascript"> <p>
function FahrToCelsius(){ <label for="Fahr">
errorMsgid = document.getElementById('errorMsg'); Temperature in Fahrenheit:
errorMsgid.innerHTML = ""; </label>
var F = document.getElementById('Fahr'); <input type="text" name ="Fahr" id="Fahr"
var C = document.getElementById('Celsius'); size="10" value="0" onChange="FahrToCelsius();" />
if (!isNaN(parseFloat(F.value))) { <span id="errorMsg"></span><br />
C.value = (5/9)*(parseFloat(F.value)- 32); <input type="text" name="Celsius" id="Celsius"
F.style.color = "green"; size="10" value="“
} else { onfocus="getElementById('Fahr').focus();" />
errorMsgid.innerHTML = in Celsius
"Please enter a Fahrenheit temperature!"; </p>
errorMsgid.className = "error"; </form>
C.value = ""; </body>
F.style.color= "red"; </html>
}
}
</script>
</head>

Web Systems [502315-3] Dr. Afnan Bukhari 37


5. Events
Events

● Some elements on the web page respond to user interactivity


(keystrokes, mouse clicks) by creating events.
○ Different kinds of elements produce different events.
○ We will concentrate on events from HTML form elements
and commonly recognized events.

● You can put handlers on HTML form elements

Web Systems [502315-3] Dr. Afnan Bukhari 39


A simple Event Handler
● The button is enclosed in a form <form method="post" action="">
○ method tells how to send the form <input type="button"
name="myButton"
data; action tells where to send it value="Click me"
onClick="alert('You clicked the button!');">
● The tag is input with attribute type = </form>
"button"
● The name can be used by other JavaScript
code
● The value is what appears on the button
● onclick is the name of the event being
handled
○ The value of the onclick element is
the JavaScript code to execute
○ alert : JavaScript code that pops up
an alert box with the given text

Web Systems [502315-3] Dr. Afnan Bukhari 40


Common Events

● Most HTML elements produce the following events:


○ onClick -- the form element is clicked
○ onDblClick -- the form element is clicked twice in close succession
○ onMouseDown -- the mouse button is pressed while over the form
element
○ onMouseOver -- the mouse is moved over the form element
○ onMouseOut -- the mouse is moved away from the form element
○ onMouseUp -- the mouse button is released while over the form
element
○ onMouseMove -- the mouse is moved
● In JavaScript, these must be spelled in all lowercase

Web Systems [502315-3] Dr. Afnan Bukhari 41


Example: Simple Rollover

● The following code will make the text Hello


red when the mouse moves over it, and
blue when the mouse moves away
<h1 onMouseOver="style.color='red';"
onMouseOut="style.color='blue';">Hello </h1>

● Image rollovers are done with the same way:


<img src="../Images/duke.gif"
width="55" height="68"
onMouseOver="src='../Images/duke_wave.gif';"
onMouseOut="src='../Images/duke.gif';">

Web Systems [502315-3] Dr. Afnan Bukhari 42


6. Events and Event
Handlers
Events and Event Handlers

● The following tables are taken from:


http://developer.netscape.com/docs/manuals/js/client/jsguide/index.htm
Event Applies to Occurs when Handler
Load Document body User loads the page in a onLoad
browser
Unload Document body User exits the page onUnload
Error Images, window Error on loading an onError
image or a window
Abort Images User aborts the loading onAbort
of an image
Web Systems [502315-3] Dr. Afnan Bukhari 44
Events and Event Handlers (cont.)

Event Applies to Occurs when Handler


KeyDown Documents, images, User depresses a key onKeyDown
links, text areas

KeyUp Documents, images, User releases a key onKeyUp


links, text areas
KeyPress Documents, images, User presses or holds onKeyPress
links, text areas down a key

Change Text fields, text User changes the value of onChange


areas, select lists an element

Web Systems [502315-3] Dr. Afnan Bukhari 45


Events and Event Handlers (cont.)

Event Applies to Occurs when Handler

MouseDow Documents, User depresses a mouse onMouseDown


n buttons, links button

MouseUp Documents, User releases a mouse onMouseUp


buttons, links button
Click Buttons, radio User clicks a form onClick
buttons, element or link
checkboxes, submit
buttons, reset
buttons, links

Web Systems [502315-3] Dr. Afnan Bukhari 46


Events and Event Handlers (cont.)

Event Applies to Occurs when Handler

MouseOver Areas, Links User moves cursor onMouseOver


over a link

MouseOut Areas, links User moves cursor onMouseOut


out of an image map
or link
Select Text fields, text User selects form onSelect
areas element’s input field

Web Systems [502315-3] Dr. Afnan Bukhari 47


Events and Event Handlers (cont.)

Event Applies to Occurs when Handler

Move Windows User or script moves onMove


a window

Resize Windows User or script resizes onResize


a window
DragDrop Windows User drops an object onDragDrop
onto the browser
window

Web Systems [502315-3] Dr. Afnan Bukhari 48


Events and Event Handlers (cont.)

Event Applies to Occurs when Handler


Focus Windows and all User gives element onFocus
form elements input focus
Blur Windows and all User moves focus to onBlur
form elements some other element
Reset Forms User clicks a Reset onReset
button

Submit Forms User clicks a Submit onSubmit


button

Web Systems [502315-3] Dr. Afnan Bukhari 49


Events and Event Handlers (cont.)
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <title>Event Example</title>
7. </head>
8. <body>

9. <p id="message">Click the button to change this text!</p>


10. <button id="myButton">Click Me</button>

11. <script>
12. // JavaScript: Event Handling
13. document.getElementById("myButton").addEventListener("click",
function() {
14. document.getElementById("message").innerText = "Text changed
after button click!";
15. });
16. </script>

17. </body>
18. </html>

Web Systems [502315-3] Dr. Afnan Bukhari 50


Events and Event Handlers (cont.)
1. <!DOCTYPE html> 19. function resetColor() {
2. <html lang="en"> 20.
3. <head> document.getElementById("text").style.color =
4. <meta charset="UTF-8"> "black";
5. <meta name="viewport" content="width=device- 21. }
width, initial-scale=1.0"> 22. </script>
6. <title>Mouse Over and Mouse Out Example</title>
7. <style> 23. </body>
8. 24. </html>
9. </style>
10. </head>
11. <body>

12. <p id="text" onmouseover="changeColor()"


onmouseout="resetColor()">
13. Hover over this text to change its color!
14. </p>

15. <script>
16. function changeColor() {
17.
document.getElementById("text").style.color = "red";
18. }

Web Systems [502315-3] Dr. Afnan Bukhari 51


7. Back to the DOM
Back to the DOM

● You can attach event handlers to HTML elements with very little
knowledge of the DOM
● However, to change what is displayed on the page requires
knowledge of how to refer to the various elements
● The basic DOM is a W3C standard and is consistent across various
browsers
○ More complex features are browser-dependent
● The highest level element (for the current page) is window, and
everything else descends from that

Web Systems [502315-3] Dr. Afnan Bukhari 53


The DOM Hierarchy

Source:
https://www.technologyuk.net/comput
ing/website-development/world-wide-
web/document-object-model.shtml

Web Systems [502315-3] Dr. Afnan Bukhari 54


Fields of window

● window
○ The current window (not usually needed).
● self
○ Same as window.
● parent
○ If in a frame, the immediately enclosing window.
● top
○ If in a frame, the outermost enclosing window.
● frames[ ]
○ An array of frames (if any) within the current window. Frames are
themselves windows.

Web Systems [502315-3] Dr. Afnan Bukhari 55


Fields of window (cont.)

● document
○ The HTML document being displayed in this window.
● location
○ The URL of the document being displayed in this window. If you set this
property to a new URL, that URL will be loaded into this window. Calling
location.reload() will refresh the window.
● navigator
○ A reference to the Navigator (browser) object. Some properties of
Navigator are:
■ appName -- the name of the browser, such as "Netscape"
■ platform -- the computer running the browser, such as "Win32"

Web Systems [502315-3] Dr. Afnan Bukhari 56


Methods of window

● alert(string)
○ Displays an alert dialog box containing the string and an OK button.
● confirm(string)
○ Displays a confirmation box containing the string along with Cancel and OK
buttons. Returns true if OK is pressed, false if Cancel is pressed.
● prompt(string)
○ Displays a confirmation box containing the string, a text field, and Cancel
and OK buttons. Returns the string entered by the user if OK is pressed, null
if Cancel is pressed.
● open(URL)
○ Opens a new window containing the document specified by the URL.
● close()
○ Closes the given window (which should be a top-level window, not a frame).
Web Systems [502315-3] Dr. Afnan Bukhari 57
20. // Confirm using window.confirm
1. <!DOCTYPE html> 21. function showConfirm() {
2. <html lang="en"> 22. const result = window.confirm("Do you want to proceed?");
3. <head> 23. window.document.getElementById("output").textContent =
4. <meta charset="UTF-8"> "Confirm result: " + result;
24. }
5. <title>JavaScript Window and Dialog
Functions</title> 25. // Prompt using window.prompt
6. </head> 26. function showPrompt() {
7. <body> 27. const name = window.prompt("What is your name?");
28. if (name !== null) {
8. <h1>JavaScript Window and Dialog Functions</h1> 29. window.document.getElementById("output").textContent = "Hello,
" + name + "!";
9. <button onclick="showAlert()">Show Alert</button> 30. } else {
10. <button onclick="showConfirm()">Show 31. window.document.getElementById("output").textContent =
"Prompt was canceled.";
Confirm</button> 32. }
11. <button onclick="showPrompt()">Show 33. }
Prompt</button>
12. <button onclick="openWindow()">Open New 34. // Open and close window using window.open and window.close
35. let newWindow;
Window</button> 36. function openWindow() {
13. <button onclick="closeWindow()">Close New 37. newWindow = window.open("https://example.com", "_blank",
Window</button> "width=400,height=300");
38. }
14. <p id="output"></p> 39. function closeWindow() {
40. if (newWindow) {
15. <script> 41. newWindow.close();
16. // Alert using window.alert 42. } else {
43. window.alert("No window is open.");
17. function showAlert() { 44. }
18. window.alert("This is an alert box!"); 45. }
19. } 46. </script>
47. </body>
48. </html>
Web Systems [502315-3] Dr. Afnan Bukhari
Thanks!

Does anyone have any questions?

Bukhari.a@tu.edu.sa

59

You might also like