WT Unit V
WT Unit V
WT Unit V
They do not have any specific order in the hierarchy. Look at the hierarchy in the
below figure.
For example:
window.name; // returns the name of window.
window.close(); // closes the browser window or tab.
Methods of Window object
JavaScript window object provides several methods that we can apply to
manipulate the web browser window.
1. alert(): This method displays an alert dialog box that contains a message and an
OK button. A single OK button allows us to dismiss alert. The general syntax is:
alert(message);
In this syntax, message is a text we pass as a parameter and is displayed in a dialog
box. Let’s take an example in which we will display an alert dialog box. It has a
message and an OK button.
<script>
function msg() {
alert("This is an Alert box");
}
</script>
<input type = "button" value = "click" onclick = "msg()"/>
When you will run this script code, click button will appear on the browser screen.
When you will click on the button, a dialog box containing a message and OK
button will appear on the web browser.
2. confirm(): This method displays a confirm dialog box, which contains a
message with two OK and Cancel buttons. The general syntax is as:
confirm(message);
Here, message is a text we pass as a parameter that will display in the dialog box.
Moreover, it returns a true value if the user click on OK button. If the user clicks
on the Cancel button, it returns false value.
The following example code shows the use of confirm() method.
<script>
let ans = window.confirm("Click on any button below");
if(ans) {
alert("You clicked on OK button");
} else {
alert("You clicked on Cancel button");
}
DEPARTMENT OF COMPUTER SCIENCE-R.SUGANYA , AP/RASC Page 3
22UCSCC53 – WEB TECHNOLOGY UNIT -5
</script>
In this example program, you will get two different alert boxes based on the user
action on the confirm() dialog box. If you click on the OK button, a message will
appear “You clicked on OK button“.
3. prompt(): This method displays a dialog box to the user and prompts the user to
enter some input in a text field. Two buttons OK and Cancel allows the user to
dismiss the dialog box with two opposite expectations:
accepting the input typed in the dialog box
canceling the entire operation
The general syntax for this method is as:
prompt(message, default_input);
This method contains two parameters, the first one is message to be displayed and
the second one is the default input typed in the text field.
When the user clicks on the OK button, this method returns a string value of the
typed entry. Otherwise, it returns null value if the user clicks on Cancel button.
Let’s take an example based on the prompt() method.
<script>
let age = prompt("How old are you?", "Please type your current age");
if(age >= 18) {
alert("You are eligible for the vote");
} else {
alert("You are not eligible for the vote");
}
</script>
4. open(): This method opens the new window. Let’s create a JavaScript program
in which we will display the content in a new window.
<script>
function msg() {
open("http://www.scientecheasy.com");
}
msg();
</script>
5. close(): This method closes the current window or tab.
Suppose you have created a FORM in an HTML document using the FORM
element and added some text fields and Buttons on the Form. On Submitting
the Form you want to validate the input or display input on another page. In
this situation, you can use a document object which is a child object of the
window object. Using the document object, you can access the elements of
the form and validate the Input.
The Document Object provides different collection elements, such as anchor
and Links which helps you to count the number of specific elements on a
form.
The Document Object also provides various properties such
as URL, bgcolor, etc. which will allow you to retrieve the details of a
document and various methods such as open(), close(), write(),
getElementById(), getElementByName(), etc. which allow you to perform
various tasks like opening an HTML document to display output and writing
a text on Web Page.
The Document Object also allows you to create cookies for a webpage by
providing a property named cookie. A cookie stores information about the
user's computer, which helps in accessing visited websites.
Now let's explore document object methods and properties.
As we know, a property of an object is the value associated with the object. The
property is accessed by using the following notation:
objectName.propertyName
where objectName is the name of the object and propertyName is the name of its
property.
Now we will show you the properties of document object in the table given below:
Properties Description
returns a report that contains all the visible and unexpired cookies
cookie
associated with the document
returns the domain name of the server from which the document
domain
has originated
documentMode returns the mode used by the browser to process the document
Properties Description
document.close()
close() closes an HTML document
Now let's take an example, to see the document object methods like open(), write(),
and getElementById() to explain their usage. See the below example:
JavaScript provides WebAPIs and Interfaces(object types) that we can use while
developing web application or website. These APIs and objects help us in
controlling the lifecycle of the webpage and performing various actions like getting
browser information, managing screen size, opening and closing new browser
window, getting URL information or updating URL, getting cookies and local
storage, etc.
There is so much that you can do using these WebAPIs and Interfaces. All the
supported Web APIs and Interfaces in JavaScript are listed on the
The Iterfaces (object types) which help us interact with the browser window are
known as Browser objects. Browser object is not an official term but its a group
of objects which belongs to different WebAPIs but are used for managing various
browser related information and actions.
For example, when an HTML document is opened in a browser window, the
browser interprets the document as a collection of hierarchical objects(HTML tags)
and accordingly displays the data contained in these objects(HTML page
rendering). The browser parses the document and creates a collection of objects,
which defines the documents and its details. We have shown the various objects
that can be used to access various components of the browser window in the
picture below:
The browser objects are of various types, used for interacting with the browser and
belongs to different APIs. The collection of these Browser objects is also known
as Browser object Model(BOM).
The default object of browser is Window which means you can call its functions
directly.
Browser Objects:
Window Object
It is used to interact with the browser window which displays the web page. It
generally represents a tab in browser, but some actions like window width and
height will affect the complete browser window.
We have covered JavaScript Window Object separately, in detail.
Navigator Object
It acts as a storehouse of all the data and information about the Browser
software used to access the webpage and this object is used to fetch information
related to the browser for example, whether the user is using Chrome browser or
Safari browser, which version of browser is being used etc.
We have covered JavaScript Navigator Object separately, in detail.
Document Object
This object represent the HTML document that is loaded into the browser. A
document object is an object that provides access to all HTML elements of a
document(webpage). We can use this object to append a new HTML tag to the
webpage, modify any exsiting HTML tag, etc.
We have covered JavaScript Document Object separately, in detail.
History Object
It stores Uniform Resource Locator(URLs) visited by a user in the browser. It is a
built-in object which is used to get browser history. This object is a property of the
JavaScript Window object.
Screen Object
It is a built-in object which is used to fetch information related to the browser
screen, like the screen size, etc. It is also obtained from the Window object.
Location Object
Location is a built-in object which represent the location of the object to which
it is linked, which can be Window or Document. Both the Document and Window
interface have a linked location property.
JavaScript Navigator Object
JavaScript Navigator Object is used to fetch information related to the
browser(useragent), like the browser name, browser version, operating system
information, etc.
JavaScript Navigator object is also a property of the JavaScript Window object and
can be accessed using the read only property window.navigator for the current
browser window.
In JavaScript, the Navigator Object includes some properties and methods which
help us to navigate from one element to another.
The properties of the navigator object are the variables created inside the Navigator
Object.
We can access Navigator Object Property
as: navigator.propertyname where propertyname is the name of property.
Properties Description
Properties Description
contains a string indicating the machine type for which the browser was
platform
compiled.
returns a string with the preferred browser language, for example, en-
language
US for English.
languages returns a string with all the languages supported by the browser in order
Properties Description
of user preference.
There are some more expreimental properties available in the Navigator object, but
the ones mentioned above are most commonly used properties.
Let's see a code example with some of these properties in action.
The Navigator object doesn't have many standardised methods, most of the
methods available are experimental.
sendBeacon() used to send a small data packet from the client to the server
The navigator object can be used for multiple specific usecases which can help you
make your website better, like:
1. Making you web app or website more compatible with different
browsers by writing specific code for different browsers to resolve
compatibility issues.
2. You can check if the browser is online or not, to show some message if the
browser is disconnected from internet.
3. You can use the location information of the user to show location specific
content.
4. You can set the preferred language as the website language if you support
multiple languages on your website.
Let's take a simple example to see the working of the screen object.
In the example below we have used the screen object to get the width and height of
the screen:
JavaScript Screen object includes some properties that are used to get browser
screen information. A table of such properties is given below.
Property Description
availWidth specifies the width of the screen, excluding the Windows taskbar
pixelDepth specifies the color Resolution, in bits per pixel, of the screen
Property Description
Now, we will take an example to clear the concepts of Screen Object Properties:
The JavaScript Screen object can be used for improving the user experience by
controlling the UI of the web app or website based on the screen size.
Example
var x = document.getElementById("myForm");
Tip: You can also access a <form> element by using the forms collection.
Example
var x = document.createElement("FORM");
Collection Description
Property Description
Method Description
JavaScript Events
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The
time is?</button>
In the example above, the JavaScript code changes the content of the element with
id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Event Description
onmouseout The user moves the mouse away from an HTML element
Event handlers can be used to handle and verify user input, user actions, and
browser actions:
Many different methods can be used to let JavaScript work with events:
Exercise:
Form validation is the process of ensuring that the data submitted through a web
form meets the required standards before it is processed or stored. The primary
purpose of form validation is to improve data accuracy, enhance security, and
provide a better user experience. By validating the data, we can prevent common
issues such as incomplete submissions, incorrect data formats, and malicious inputs.
There are two main types of form validation:
1. Client-Side Validation:
Definition: This type of validation occurs in the user’s browser before the data
is sent to the server. JavaScript is commonly used to perform client-side
validation.
Purpose: It provides immediate feedback to the user, allowing them to correct
errors in real-time without needing to reload the page.
Examples: Checking if required fields are filled, verifying email format, and
ensuring password strength.
2. Server-Side Validation:
Definition: This type of validation takes place on the server after the data has
been submitted. Server-side validation is crucial for security and data integrity.
Purpose: It acts as a final check to ensure that all submitted data meets the
necessary criteria before it is processed or stored. Server-side validation is
essential to protect against malicious inputs and ensure data consistency.
Examples: Sanitizing input data, checking for SQL injection attacks, and
confirming that all required fields are present.
Both client-side and server-side validations are essential for creating robust and
secure web applications. While client-side validation enhances user experience,
server-side validation ensures comprehensive data security.
FORM ENHANCEMENTS
HTML5 includes a variety of new input types that cater to specific data needs,
reducing the need for additional JavaScript validation:
New Attributes
placeholder: Shows a hint to the user about what to enter in the input field.
required: Specifies that an input field must be filled out before submitting
the form.
pattern: Defines a regex pattern that the input field value must match.
autocomplete: Helps the browser predict the user’s input based on previous
inputs.
autofocus: Automatically focuses the input when the page loads.
multiple: Allows multiple values/file selections for input types
like email or file.
Example Usage
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="100">
<label for="homepage">Homepage:</label>
<input type="url" id="homepage" name="homepage"
placeholder="https://example.com">
JavaScript Libraries
A JavaScript library is a collection of classes, methods, and pre-written functions
that developers can use in their web development projects. Libraries make code
reusable and simplify the development process. They are also favored for their
cross-browser compatibility, saving developers time and effort. Some popular
JavaScript libraries include:
JavaScript
Versions Description Applications
Libraries
A JavaScript library
Provides cross-
that is fast, small, and
browser
Introduced: August rich in features.
compatibility
jQuery 26, 2006 Helps in DOM
and it
Current: 3.7.1 manipulation and
simplifies the
event handling in web
code.
applications.
JavaScript
Versions Description Applications
Libraries
An HTML5-based
user interface system
Creates
designed to make
Introduced: October responsive and
responsive websites
jQuery Mobile 16, 2010 Ajax-based
and apps.
Current: 1.5.0 user interface
Accessible on all
system.
smartphone, tablet,
and desktop devices.
A popular front-end
library with a set of
React components that
are designed for the Provides
middle platform and customizable
React Suite Current: 5.43.0 back-end products. themes,
The input component accessibility
allows the user to support.
create a basic widget
for getting the user
input in a text field.
JavaScript
Versions Description Applications
Libraries
desktop
complexinterfaces.
applications
Provides
A JavaScript library Modularity and
Introduced: April 23 that has large amout of fast web
Lodash , 2012 functions. application by
Current: 4.17.21 It has built-in the use of
functions. built-in
functions.
A JavaScript package
Used in a
that makes it simple to
browser using
parse, validate,
the script
manipulate, and
approach.
Introduced: 2011 display date/time in
Moment.js Compatible
Current: 2.29.4 JavaScript.
with Node.js
Allows you to display
and can be
dates in a human-
installed via
readable format based
npm.
on your location.
A resource JavaScript
Provide
library for managing
applications
documents based on
that has DOM
Introduced: 2011 data.
D3.js manipulation,
Current: 7.8.5 One of the most
Transition,
effective framework to
animatioin,
work on data
large dataset
visualization.
JavaScript
Versions Description Applications
Libraries
making code
run on any web
accessible and
browser.
inclusive for artists.
Provides
Lightweight
JavaScript
JavaScript library and
templating,
not a complete
function
Introduced: October framework that was
binding, deep
Underscore.js 28, 2009 written by Jeremy
equality
Current: 1.13.6 Ashkenas.
testing,
Provides utility
creating quick
functions for a variety
indexes, and
of use.
many more.