0% found this document useful (0 votes)
10 views55 pages

Module 1 Lesson 1 3

This document provides an overview of JavaScript programming, detailing its history, purpose, and key features. It explains the evolution of JavaScript from its inception in the 1990s to its current role as a dynamic scripting language essential for web development. Additionally, it covers the advantages of using JavaScript, its basic syntax, common HTML elements, and limitations.
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)
10 views55 pages

Module 1 Lesson 1 3

This document provides an overview of JavaScript programming, detailing its history, purpose, and key features. It explains the evolution of JavaScript from its inception in the 1990s to its current role as a dynamic scripting language essential for web development. Additionally, it covers the advantages of using JavaScript, its basic syntax, common HTML elements, and limitations.
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

Learning Outcomes:

use JavaScript as an
interactive tool for web
AN OVERVIEW OF development
JAVASCRIPT PROGRAMMING hand code a number of
interactive processes
implement interactive
responses in your web pages
modify CSS styles and
presentation properties with
JavaScript
control images as interactive
objects
use JavaScript for specific
tasks effectively and have the
confidence to explore it
further.
Learning Outcomes:
Learn about the
different types of
Introduction of JavaScript
Operators
Introduction
JavaScript is a cross-platform, object-oriented scripting language used to make webpages
interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are
also more advanced server side versions of JavaScript such as Node.

History of JavaScript
JavaScript is arguably one of the most important languages today. The rise of the web
has taken JavaScript places it was never conceived to be. We take a look at how
JavaScript has evolved in its short history, and where it is headed. Read on!

"We take a look at how JavaScript has evolved in its short history, and where it is
headed!"

It All Began in the 90s


It all happened in six months from May to December 1995. Netscape Communications
Corporation had a strong presence in the young web. Its browser, Netscape
Communicator, was gaining traction as a competitor to NCSA Mosaic, the first popular
web browser. Netscape was founded by the very same people that took part in the
development of Mosaic during the early 90s, and now, with money and independence,
they had the necessary freedom to seek further ways to expand the web. And that is
precisely what gave birth to JavaScript.
Marc Andreessen, founder of Netscape Communications and part of the ex-Mosaic
team, had the vision that the web needed a way to become more dynamic. Animations,
interaction and other forms of small automation should be part of the web of the future.
So the web needed a small scripting language that could interact with the DOM (which
was not set in stone as it is right now). But, and this was an important strategic call at
the time, this scripting language should not be oriented to big-shot developers and
people with experience in the software engineering side of things. Java was on the rise
as well, and Java applets were to be a reality soon. So the scripting language for the
web would need to cater to a different type of audience: designers. Indeed, the web
was static. HTML was still young and simple enough for non-developers to pick up. So
whatever was to be part of the browser to make the web more dynamic should be
accessible to non-programmers. And so the idea of Mocha was born. Mocha was to
become a scripting language for the web. Simple, dynamic, and accessible to non-
developers.
This is when Brendan Eich, father of JavaScript, came into the picture. Eich was
contracted by Netscape Communications to develop a "Scheme for the browser".
Scheme is a Lisp dialect and, as such, comes with very little syntactic weight. It is
dynamic, powerful, and functional in nature. The web needed something of the sort:
easy to grasp syntactically; dynamic, to reduce verbosity and speed up development;
and powerful. Eich saw a chance to work on something he liked and joined forces.
At the moment there was a lot of pressure to come up with a working prototype as
soon as possible. The Java language, née Oak at the time, was starting to get traction.
Sun Microsystems was making a big push for it and Netscape Communications was
about to close a deal with them to make Java available in the browser. So why Mocha
(this was the early name for JavaScript)? Why create a whole new language when
there was an alternative? The idea at the time was that Java was not suited for the
type of audience that would consume Mocha: scripters, amateurs, designers. Java was
just too big, too enterprisy for the role. So the idea was to make Java available for big,
professional, component writers; while Mocha would be used for small scripting tasks.
In other words, Mocha was meant to be the scripting companion for Java, in a way
analogous to the relationship between C/C++ and Visual Basic on the Windows
platform.

What is JavaScript?
JavaScript is a scripting language that is one of the three core languages used to
develop websites. Whereas HTML and CSS give a website structure and style,
JavaScript lets you add functionality and behaviors to your website, allowing your
website’s visitors to interact with content in many imaginative ways.
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script
to interact with the user and make dynamic pages. It is an interpreted programming
language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript
made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript
language.

 JavaScript is a lightweight, interpreted programming language.


 Designed for creating network-centric applications.
 Complementary to and integrated with Java.
 Complementary to and integrated with HTML.
 Open and cross-platform

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.

Advantages of JavaScript
The merits of using JavaScript are −
 Less server interaction − You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your
server.
 Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.

HTML Documents and Basic Syntax


HTML is using tags for its syntax. A tag is composed with special characters: <, > and /. They are
interpreted by softwares to compose an HTML element.

Common HTML Elements


This section briefly describes the important behaviour, attributes, and rules for each of
the common HTML elements.
<html>

Must have exactly one head element followed by exactly one body element. No
attributes of interest.
<head>

Only allowed within the html element. Must have exactly one title. May also
contain link elements to refer to external CSS files and/or style elements for
inline CSS rules. No attributes of interest.
<title>

Must go in the head element and must only contain text. Information for the
computer to use to identify the web page rather than for display, though it is
often displayed in the title bar of the browser window. No attributes.
<link>

An empty element that must go in the head element. Important attributes


are: rel, which should have the value "stylesheet"; href, which specifies the
location of a file containing CSS code (can be a URL); type, which should have
the value "text/css". The media attribute may also be used to distinguish
between a style sheet for display on "screen" as opposed to display in "print".

Other sorts of links are also possible, but are beyond the scope of this book.
<body>

Only allowed within the html element. Should only contain one or more block-
level elements, but most browsers will also allow inline elements. Various
appearance-related attributes are possible, but CSS should be used instead.
<p>

A block-level element that can appear within most other block-level elements.
Should only contain inline elements (words and images). Automatically
typesets the contents as a paragraph (i.e., automatically decides where to break
lines). May have the common attributes class and style.
<img>

An empty, inline element (i.e., images are treated like words in a sentence).
Can be used within almost any other element. Important attributes are src, to
specify the file containing the image (this may be a URL, i.e., an image
anywhere on the web), and alt to specify alternative text for non-graphical
browsers.
<a>

Known as an anchor. An inline element that can go inside any other element. It
can contain any other inline element (except another anchor). Important
attributes are: href, which means that the anchor is a hypertext link and the
value of the attribute specifies a destination (when the content of the anchor is
clicked on, the browser navigates to this destination); name, which means that
the anchor is the destination for a hyperlink.

The value of an href attribute can be: a URL, which specifies a separate web
page to navigate to; something of the form #target, which specifies an anchor
within the same document that has an attribute name="target"; or a
combination, which specifies an anchor within a separate document. For
example,
[Link]
specifies the top of the W3C page for HTML 4.01 and
[Link]
specifies the table of contents further down that web page.
<h1> ... <h6>

Block-level elements that denote that the contents are a section heading. Can
appear within almost any other block-level element, but can only contain inline
elements. No attributes of interest. These should be used to indicate the section
structure of a document, not for their default display properties. CSS should be
used to achieve the desired weight and size of the text in headings.
<table>, <tr>, and <td>

A table element contains one or more tr elements, each of which contains one
or more td elements (so td elements can only appear within tr elements, which
can only appear within table elements). A table element may appear within
almost any other block-level element. In particular, a table can be nested within
the td element of another table.

The table element has a summary attribute to describe the table for non-
graphical browsers. There are also attributes to control borders, background
colours, and widths of columns, but CSS is the preferred way to control these
features.
The tr element has attributes for the alignment of the contents of columns,
including aligning numeric values on decimal points. There are no
corresponding CSS properties.

The td element also has alignment attributes for the contents of a column for
one specific row, but these can be handled via CSS instead. However, there are
several attributes specific to td elements, in
particular, rowspan and colspan which allow a single cell to spread across more
than one row or column.

Unless explicit dimensions are given, the table rows and columns are
automatically sized to fit their contents.

It is tempting to use tables to arrange content on a web page, but it is


recommended to use CSS for this purpose instead. Unfortunately, the support
for CSS in web browsers tends to be worse for CSS than it is
for table elements, so it may not always be possible to use CSS for arranging
content. This warning also applies to controlling borders and background
colours via CSS.

An example of a table with three rows and three columns:


<table>
<tr>
<td></td> <td>pacific</td> <td>eurasian</td>
</tr>
<tr>
<td>min</td> <td>276</td> <td>258</td>
</tr>
<tr>
<td>max</td> <td>283</td> <td>293</td>
</tr>
</table>

It is also possible to construct more complex tables with separate thead, tbody,
and tfoot elements to group rows within the table (i.e., these three elements
can go inside a table element, with tr elements inside them).
<hr>

An empty element that produces a horizontal line. It can appear within almost
any block-level element. No attributes of interest. This entire element can be
replaced by CSS control of borders.
<br>
An empty element that forces a new line or line-break. It can be put anywhere.
No attributes of interest. This element should be used sparingly. In general, text
should be broken into lines by the browser to fit the available space.
<ul>, <ol>, and <li>

A ul or ol element contains one or more li elements. Anything can go inside


an li element (i.e., you can make a list of text descriptions, a list of tables, or
even a list of lists). The former case produces a bullet-point list and the latter
produces a numbered list. These elements have no attributes of interest. CSS
can be used to control the style of the bullets or numbering and the spacing
between items in the list.

It is also possible to produce “definition” lists, where each item has a heading.
Use a dd element for the overall list with a dt element to give the heading and
a dd element to give the definition for each item.
<pre>

Block-level element that displays any text content exactly as it appears in the
source code. Good for displaying computer code. It is possible to have other
elements within a pre element. No attributes of interest. Like the hr element,
this element can usually be replaced by CSS styling.
<div> and <span>

Generic block-level and inline (respectively) elements. No attributes of interest.


These can be used as “blank” elements with no predefined appearance
properties. Their appearance can then be fully specified via CSS. In theory, any
other HTML element can be emulated using one of these elements and
appropriate CSS properties. In practice, the standard HTML elements are more
convenient for their default behaviour and these elements are used for more
exotic situations.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −
 Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
 JavaScript cannot be used for networking applications because there is no such
support available.
 JavaScript doesn't have any multi-threading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows
you to build interactivity into otherwise static HTML pages.

JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your
web page, but it is normally recommended that you should keep it within
the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.

The script tag takes two important attributes −


 Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like −

Your First JavaScript Code


Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser
that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a
comment in JavaScript, so we add that to prevent a browser from reading the end of
the HTML comment as a piece of JavaScript code. Next, we call a
function [Link] which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following
code.
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.

Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line. For example, the
following code could be written without semicolons.
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.

Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
 Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.

All the modern browsers come with built-in support for JavaScript. Frequently, you may
need to enable or disable this support manually. This chapter explains the procedure of
enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox,
chrome, and Opera.

JavaScript in Internet Explorer


Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
 Follow Tools → Internet Options from the menu.
 Select Security tab from the dialog box.
 Click the Custom Level button.
 Scroll down till you find Scripting option.
 Select Enable radio button under Active scripting.
 Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to
select Disable radio button under Active scripting.

JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox −
 Open a new tab → type about: config in the address bar.
 Then you will find the warning dialog. Select I’ll be careful, I promise!
 Then you will find the list of configure options in the browser.
 In the search bar, type [Link].
 There you will find the option to enable or disable javascript by right-clicking on
the value of that option → select toggle.
If [Link] is true; it converts to false upon clicking toogle. If javascript is
disabled; it gets enabled upon clicking toggle.

JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome −
 Click the Chrome menu at the top right hand corner of your browser.
 Select Settings.
 Click Show advanced settings at the end of the page.
 Under the Privacy section, click the Content settings button.
 In the "Javascript" section, select "Do not allow any site to run JavaScript" or
"Allow all sites to run JavaScript (recommended)".

JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera −
 Follow Tools → Preferences from the menu.
 Select Advanced option from the dialog box.
 Select Content from the listed items.
 Select Enable JavaScript checkbox.
 Finally click OK and come out.
To disable JavaScript support in your Opera, you should not select the Enable
JavaScript checkbox.

Warning for Non-JavaScript Browsers


If you have to do something important using JavaScript, then you can display a
warning message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows

 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.

JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows −
JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in the
page, then the script goes in the <body> portion of the document. In this case, you
would not have any function defined using JavaScript. Take a look at the following
code.
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as follows −
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages of a
site.
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.

To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.
For example, you can keep the following content in [Link] file and then you can
use sayHello function in your HTML file after including the [Link] file.

JavaScript Data types


One of the most fundamental characteristics of a programming language is the set of
data types it supports. These are the type of values that can be represented and
manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
 Numbers, eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript
supports a composite data type known as object. We will cover objects in detail in a
separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-
point values. All numbers in JavaScript are represented as floating-point values.
JavaScript represents numbers using the 64-bit floating-point format defined by the
IEEE 754 standard.

JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.

Storing a value in a variable is called variable initialization. You can do variable


initialization at the time of variable creation or at a later point in time when you need
that variable.
For instance, you might create a variable named money and assign the value 2000.50
to it later. For another variable, you can assign a value at the time of initialization as
follows.
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable will hold. The value type of a
variable can change during the execution of a program and JavaScript takes care of it
automatically.

JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.
 Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the
same name as a global variable, you effectively hide the global variable. Take a look
into the following example.
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For
example, break or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
 JavaScript variable names are case-sensitive. For
example, Name and name are two different variables.

JavaScript Reserved Words


A list of all the reserved words in JavaScript are given in the following table.
They cannot be used as JavaScript variables, functions, methods, loop labels, or any
object names.
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and ‘+’ is called the operator. JavaScript supports the following types
of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then –
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Example
The following code shows how to use comparison operators in JavaScript.
Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −
Example
Try the following code to learn how to implement Logical Operators in JavaScript.

Bitwise Operators
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
Example
Try the following code to implement Bitwise operator in JavaScript.
Assignment Operators
JavaScript supports the following assignment operators −
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=.
Example
Try the following code to implement assignment operator in JavaScript.
Learning Outcomes:
Learn about what
JavaScript can do on
making a webpage
Learn about how to
start a basic program
Printing Text on a Web Page

Printing Text on a Web Page


In this chapter, we will learn how to print messages on a web page using the [Link] statement.
In Object-Oriented Programming (OOP) jargon, this statement using the dot (.) operator specifies first
the object which is the word document while the word write is the method of the object. The method is
the action to be performed on the object.

What JavaScript Can Really Do?


To put things simply, JavaScript is an object orient programming language designed to
make web development easier and more attractive. In most cases, JavaScript is used to
create responsive, interactive elements for web pages, enhancing the user experience.

Things like menus, animations, video players, interactive maps, and even simple in-
browser games can be created quickly and easily with JavaScript.

Three different languages work together to enable the creation of modern web pages.
These are:
 CSS, which is used to style the content that has been inserted using HTML.
Following on from the example above, CSS would allow you to change the
shape, size, color, and style of the login button you added with HTML.
 HTML, or hypertext markup language, which is used to put content onto a page.
It allows the inclusion of things like text, images, links, and even videos. For
example, HTML would allow you to put a login button in a certain position on
your webpage.
 JavaScript, which is the focus of this tutorial. JavaScript allows you to take
ordinary web elements and make them interactive. It can be used alongside
your HTML and CSS and is an extremely important tool for any web developer.

How to Embed JavaScript in HTML


You can add JavaScript code in an HTML document by employing the dedicated HTML
tag <script> that wraps around JavaScript code.

The <script> tag can be placed in the <head> section of your HTML or in
the <body> section, depending on when you want the JavaScript to load.

Generally, JavaScript code can go inside of the document <head> section in order to
keep them contained and out of the main content of your HTML document.

However, if your script needs to run at a certain point within a page’s layout — like
when using [Link] to generate content — you should put it at the point
where it should be called, usually within the <body> section.

Let’s consider the following blank HTML document with a browser title of Today's
Date:
This will enable the webpage to display an alert with the current date regardless of when
the user loads the site.

In order to achieve this, we will add a <script> tag along with some JavaScript code
into the HTML file.

To begin with, we’ll add the JavaScript code between the <head> tags, signalling the
browser to run the JavaScript script before loading in the rest of the page. We can add
the JavaScript below the <title> tags, for instance, as shown below:
Now let us have our first example, to learn JavaScript right away. If you want to learn you must try it on
your own so that you can explore!

Note: If you are going to save your work make sure to end it with .htm (For example: [Link])
not html!

Example 1:

Output:

Example 2:
Output:

Example 3:

Output:
Example 4:

Output:

Example 5:
Output:
Learning Outcomes:
Learn about on how to
use the windows Object
and Its methods
Learning Event-Handlers

JavaScript events are specific actions or proceedings that happen in the program
or website you are developing. You can set up a response which will be triggered
by specified events. For example, JavaScript mouse events refer to various cursor
movements over elements.

In this chapter, you'll learn what JavaScript event handlers are, how to create
JavaScript events, and how to add JavaScript button events and browser events.
You'll also grasp how, why, and where you can add events with JavaScript to
increase the quality of your site, make it more polished and user-friendly.

JavaScript Events: Main Tips

 Anything that happens to an HTML element using JavaScript is called a


JavaScript event.

 JavaScript can execute some specific code when a particular event


happens.

 A JavaScript event can be something that a user does (e.g., clicking on


an HTML element) or something that a browser does (e.g., finishing
loading a page).
Events: What and When?

Keep in mind that HTML event attributes can run JavaScript directly or
through a function. The functions can and should be created by you. This way
they will suit your needs best.

You can also prevent JavaScript events from being handled. JavaScript event
handlers can be useful when you want to execute a particular functionality
when something changes on the web page.

These are the most common web page events:

 A page loads

 User clicks a button

 User inputs data

Event Handler Attributes

JavaScript event handler attributes can be inserted into HTML elements. In


the example below, you can see one of the simplest JavaScript button events.
A JavaScript event handler attribute onclick is added to an HTML button
element.

When the user clicks the button, a JavaScript event occurs. Also, the code
defines what to do when that event occurs:
Event handlers are meant to be embedded so they are not required to have
the <script> and </script> tags. In other words, these event handlers are not
scripts but are small interfaces that allow for interaction between the webpage
and the surfer.

We have here the list of common JavaScript Events that we will use in our
program.

Examples of using JavaScript to react to events

Input Events
Mouse Events

Click Events

Load Events

Window Object And Its Methods In Javascript


JavaScript Window is a global Interface (object type) which is used
to control the browser window lifecycle and perform various
operations on it.

A global variable window, which represents the current browser


window in which the code is running, is available in our JavaScript
code and can be directly accessed by using window literal.
It represents a window containing a webpage which in turn is
represented by the document object. A window can be a new window,
a new tab, a frame set or individual frame created with JavaScript.

In case of multi tab browser, a window object represents a single


tab, but some of its properties like innerHeight, innerWidth and methods
like resizeTo() will affect the whole browser window.

Whenever you open a new window or tab, a window object


representing that window/tab is automatically created.

The properties of a window object are used to retrieve the information


about the window that is currently open, whereas its methods are
used to perform specific tasks like opening, maximizing, minimizing
the window, etc.

To understand the window object, let's use it to perform some


operations and see how it work.

Using JavaScript Window Object

Let's use the JavaScript window object to create a new window, using
the open() method. This method creates a new window and returns an
object which further can be used to manage that window.
In the code above, we have used the window object of the existing
window to create a new window using the open() method. In
the open() method we can provide the URL to be opened in the new
window(we can keep it blank as well), name of the window,
the width and the height of the window to be created.

Following is the syntax for the window object open() method:

We can provide, as many properties as we want, while creating a new


window.
When the open() method is executed, it returns the reference of the
window object for the new window created, which you can assign to a
variable, like we have done in the code above. We have assigned the
value returned by the [Link]() method to the win variable.

The we have used the win variable to access the new window, like
getting the name of the window, getting location of the window which
opened the new window etc.

There are many properties and methods for the window object, which
we have listed down below.

Find Dimensions of a Window

We can get the height and width of a window by using the window
object built-in properties.
We can also access the document object using a window
object([Link]) which gives us access to the HTML document,
hence we can add new HTML element, or write any content to the
document, like we did in the example above.

JavaScript Window Object Properties


The wondow object properties refer to the variables created inside the
windows object.

In JavaScript, all the available data is attached to the window object as


properties.

We can access window object's properties


like: [Link] where propertyname is the name of property.

A table of most popular window object properties is given below:

Property Description

returns a boolean value that specifies whether a window has been closed
closed
or not

document specifies a document object in the window.

history specifies a history object for the window.

frames specifies an array of all the frames in the current window

specifies the default message that has to be appeared in the status bar of
defaultStatus
Window.
Property Description

innerHeight specifies the inner height of the window's content area.

innerWidth specifies the inner width of the window's content area.

length specifies the number of frames contained in the window.

location specifies the location object for window

name specifies the name for the window

top specifies the reference of the topmost browser window.

self returns the reference of current active frame or window.

parent returns the parent frame or window of current window.

specifies the message that is displayed in the status bar of the window
status
when an activity is performed on the Window.

screenleft specifies the x coordinate of window relative to a user's monitor screen

screenTop Specifies the y coordinate of window relative to a user's monitor screen

screenX specifies the x coordinate for window relative to a user's monitor screen

screenY Specifies the y coordinate for window relative to a user's monitor screen
Let's take an example to see a few of these properties in action:

In the example above, we have created a new window, just to make


you familiar with new window creation and also, to make you
understand that when we create a new window, then the current
window has a different window object and the new window will have a
separate window object.
We have then tried to access some properties of the new window
created.

TASK: Try some more windows property in the above code


playground to practice and understant how window properties work.

JavaScript Window Object Methods

The window object methods refer to the functions created inside the
Window Object, which can be used to perform various actions on the
browser window, such as how it displays a message or gets input from
the user.

Below we have listed down some of the most commonly used window object
methods:

Method Description

specifies a method that displays an alert box with a message


alert()
an OK button.

specifies a method that removes the focus from the current


blur()
window.

specifies a method that clears the timer, which is set by


clearInterval()
using setInterval() method.

close() specifies a method that closes the current window.

specifies a method that displays a dialogue box with a


confirm()
message and two buttons OK and Cancel

focus() specifies a method that sets the focus on current window.


Method Description

open() specifies a method that opens a new browser window

moveTo() specifies a method that moves a window to a specified position

moveBy() specifies a Method that moves a window relative to its current position.

prompt() specifies a method that prompts for input.

specifies a method that sends a print command to print the content of the
print()
current window.

specifies a method that evaluates an expression after a specified number of


setTimeout()
milliseconds.

specifies a method that evaluates an expression at specified time intervals


setInterval()
(in milliseconds)

resizeBy() specifies the amount by which the window will be resized

resizeTo() used for dynamically resizing the window

scroll() scrolls the window to a particular place in document

scrollBy() scrolls the window by the given value

stop() this method stops window loading


Let's take an example and see a few of the above methods in action:

You might also like