Module 1 Lesson 1 3
Module 1 Lesson 1 3
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!"
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.
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.
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>
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 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>
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>
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.
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 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.
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 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.
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
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.
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.
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.
A page loads
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.
Input Events
Mouse Events
Click Events
Load Events
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.
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.
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.
Property Description
returns a boolean value that specifies whether a window has been closed
closed
or not
specifies the default message that has to be appeared in the status bar of
defaultStatus
Window.
Property Description
specifies the message that is displayed in the status bar of the window
status
when an activity is performed on the Window.
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:
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
moveBy() specifies a Method that moves a window relative to its current position.
specifies a method that sends a print command to print the content of the
print()
current window.