JavaScript - For Beginners - Francis John Thottungal
JavaScript - For Beginners - Francis John Thottungal
1 Overview
2 First Program
3 Variables
4 Operators
5 Conditions
6 Loops
7 Functions
8 Events
9 Objects
10 Number
11 Boolean
12 Strings
13 Arrays
14 Date
15 Actions in Math
16 Regular Expressions
17 Refresh and Redirect
18 Cookies
19 DHTML
20 Browser Windows
21 Moving Objects
22 Appendix I- Creating a simple drop down menu
Overview
JavaScript is a language for the world wide web. All websites use hyper text
markup language(html) as the base for making a website. There are pages that
are written in more advanced languages such as ASP, PHP, Python etc but the
base still remains html. The hypertext markup language had limitations and
these limitations are addressed by several languages including JavaScript.
Languages such as ASP, PHP, Python etc allow a website to interact with
servers and external files when needed. They bring in a dynamism with
relation to the server and external objects. Thus when a form is required to be
filled and its details have to be saved these languages come into play.
JavaScript on the other hand like html is a client side language that makes the
web pages lively. Floating surveys, greetings, interactive forms which has
certain life to it, light weight games etc are some of its functions on the
website.
Less server interaction: JavaScript can be used validate user input before
sending the page off to the server.
Immediate feedback to the visitors: JavaScript can help users of a webpage
with info immediately without server connection.
Increased interactivity: Messages and dynamism can be added when mouse
moves over parts and objects of a webpage.
Richer interfaces: Drop down menus etc can help the user to have a rich
experience at the webpage.
JavaScript is an interpreted language which is lightweight and makes an
otherwise static page made through html into something dynamic.
Before we start:
So find the browser that is on the computer and see the following:
Internet Explorer
Firefox
Open a new tab -> type about: config in the address bar.
Find the warning dialog. Select I’ll be careful, I promise!
Find the list of configure options in the browser.
In the search bar, type JavaScript. Enabled.
Find the option to enable or disable JavaScript by right-clicking on the value
of that option -> select toggle.
Google Chrome
Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
Show advanced settings at the end of the page.
Under 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)".
The tools needed to JavaScript is the program notepad or similar editor and a
browser. Initially an internet connection may not be required but having a
connection on the computer can greatly help in more advanced programming
that one will make down the line.
The JavaScript will be part of the html website. It could be encapsulated into
pages where there is a mix of html and other languages. However, the
examples in this book will be largely with html code.
1. It is case sensitive.
3. JavaScript ignores spaces, tabs, and newlines that appear in the programs.
Therefore, spaces, tabs, and newlines can be used freely in a program to make
it presentable and readable.
4. Any text between a // and the end of a line is treated as a comment. Any text
between the characters /* and */ is used for large comments. JavaScript also
recognizes <! --. as a single-line comment, just as it does the // comment. The
closing comment should be written as //-->.
This book will use the C style approach of // for single comments and /* */ for
larger comments.
Chapter 1. First Program
<html>
<body>
<script language="javascript" type="text/javascript">
document.write ("Hello World!")
</script>
<noscript>
Sorry!!!JavaScript is needed.
</noscript>
</body>
</html>
So in notepad or similar editor save this code with the extension .html. In this
case hello.html. Observe the file with Explorer/Chrome/Firefox. How to do
that? First save file as hello.html say on the desktop or any folder on your
computer. Point the mouse to the file and right click. Choose open with and
choose the browser of your choice. Test the code on as many browsers as is
available on the computer.
In the code above and in all JavaScript codes the <script language=> </script>
is required. It tells the browser that what is in between these tags are related to
JavaScript. The placement of the script tags can be in any four places as
follows:
3. Between <head> and </head> and also between <body> and </body>. In
this case generally a declaration of JavaScript function etc. is made in the
head section and referenced in the body location where it is needed.
If the JavaScript code is in case two above, then as the web page loads the
contents or action written within the code will run automatically. If the code is
shared on many pages then it is possible to create a text file with extension
“.js” that contains the JavaScript code. In this case the script tag will look like
this:
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
Filename can be any name that makes sense with respect to the website being
developed. To prevent browsers from showing the code if they do not support
JavaScript for any reason one could use the following format when writing
code in JavaScript.
<body>
<script language=”JavaScript”>
<!--
document.write(“Hello”);
// -->
</script>
</body
The tags <!-- and corresponding //--> will make sure that no code is shown if
JavaScripting is not available on the browser being used. A way to check to if
JavaScript is as follows: The response is either true or false.
<html>
<body>
<script language="JavaScript">
<!--
var haveJava = navigator.javaEnabled();
document.write("Java is enabled: " + haveJava);
// -->
</script></body></html>
Chapter 2. Variables
Variables exist in all programming languages. They hold temporarily various
types of data and perform actions on them as required by the programmer.
It also supports objects and two trivial data types null and undefined. Note that
JavaScript is case sensitive. JavaScript stores numbers in the floating point
representation.
<html>
<body>
<script language="javascript" type="text/javascript">
var book = "Javascript-made easy";
document.write(book);
</script>
</body>
</html>
Notice here the placement of the <script> tags are in the body of the html page.
The variable was defined and the value of the variable was asked to be written
in the body of the html page.
Similarly, one could define variables for numbers. The difference is that for
numbers there is no quotation marks like for the string shown above. Unlike
other programming languages there is no need to mention if a number is an
integer, or a float or a double because JavaScript uses a float representation
for all numbers.
Names of variables have to be unique and have some relevant meaning with
respect to the program being created. If local variable name and global
variable name is the same then within the function the local variable name will
take precedence over the global variable name.
Like any programming language JavaScript has some reserved words that
cannot be used as variable names. In addition to these reserved words the
following
Names should not start with a numeral (0-9). Names must begin with a letter or
an underscore character. JavaScript is case sensitive therefore x and X are two
different variable names.
A program once written might look foreign after many months or years if one
has to update or it and having an understandable program will greatly help in
such an event.
Chapter 3. Operators
Operators act on variables and constants and exist in every programming
language and in math.
The five arithmetical operators that are common to almost all languages and
something one is familiar with from mathematics.
They are:
Operator Description
+ Addition
- Substraction
* Multiplication
/ Division
% Modulus
++ Increment by one
-- Decrement by one
The modulus operator gives the remainder of a division of two values: For
example:
x = 10 % 4; will give the value of 2 to x. Let us look at an example:
<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 50;
var y = 10;
document.write("x + y = ");
result = x + y;
document.write(result);
document.write("<br>");
document.write("x - y = ");
result = x - y;
document.write(result);
document.write("<br>");
document.write("x % y = ");
result = x % y;
document.write(result);
</script>
</body>
</html>
The output is 60, 40 and 0 respectively for the three arithmetic operations done
in the above program. Note that entire script was written within the body of the
html page. The values are calculated in result variable and are separated from
the value of each equation by using the <br> tag of html.
Relational and comparison operators (== , !=, >, <, >=, <= )
Two expressions can be compared using relational and equality operators. The
result of such an operation is either true or false. The relational operators in
JavaScript are:
Operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 50;
var y = 10;
The assignment operator (=) is not the same as the relational operator (= =).
One assigns the value on the right hand side to the variable on the left and the
other compares whether values on both sides of the operator are equal. The
answer for the above program will be false. Try with the other operators and
see the result.
<html>
<body>
<script language ="javascript" type="text/javascript">
<!--
var x = true;
var y = false;
document.write("And operation");
result = x && y;
document.write("<br>");
document.write(result);
document.write("<br>");
document.write("Or operation");
result = x || y;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>
x y x && y
True True True
True False False
False True False
False False False
The || logical operator is equivalent to the Boolean logical operation OR which
has the following truth table.
x y x || y
True True True
True False True
False True True
False False False
The conditional operator returns one value if the expression evaluates to true
and a different one if the expression evaluates to false. Its syntax is:
This is similar to using the IF condition. We will discuss this in the controls
chapter.
For now:
<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 9;
var y = 11;
var Y = "Yes";
var N = "No";
document.write("Condition operation");
result = (x > y) ? Y: N;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>
The result will be no 9 is less than 11. Reverse the query and see the result.
Bitwise operators (&, |, ^ , ~ , << , >> , >>>)
Modify variables considering the bit patterns representing the values they
store.
<html>
<body>
<script language ="javascript" type="text/javascript">
var x = 9;
var y = 11;
document.write("& operation");
result = x & y;
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>
The result will be 9. Now try the other operators with the same numbers.
In addition to the = assignment operator there are other operators such as the
following:
typeof Operator
The typeof operator is a unary operator. It is placed before its single operand,
which can be of any type.
<html>
<body>
<script language ="javascript" type="text/javascript">
<!--
var x = 9;
document.write("Result is");
result = (typeof x == "string" ? "x is string" :"x is
numeric");
document.write("<br>");
document.write(result);
document.write("<br>");
</script>
</body>
</html>
If the condition is true, a certain is action done otherwise another set of actions
will be done.
Therefore, we have If, If. Else and third option in JavaScript is If..else if…
statements.
<html>
<body>
<script language ="javascript" type="text/javascript">
var grade = 87;
if ((grade > 90) && (grade <=100))
{
document.write("Your grade is A");
}
else if ((grade >= 80) && (grade < 90))
{
document.write("Your grade is B");
}
else if
((grade >=70) && (grade < 80))
{
document.write("Your grade is C");
}
else
{
document.write (" Your grade is F");
}
</script>
</body>
</html>
In the example above we have used all three to demonstrate the grading of a
particular subject. The program starts with a ‘If’ condition followed by a ‘else
if’. Finally, if none of the grade options were relevant the grade would be a ‘F’
by virtue of the last ‘else’ condition.
One must not forget to put { } brackets after statements. In this example there
are two conditions to satisfy and they are joined together by an and operator
(&&). Both conditions have to be true to run the statements enclosed within {}.
JavaScript does not require the semicolon after each statement but out of habit
from other languages it is best to keep the convention especially if one
programs in multiple languages.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The format above is used by the switch statement. The break states for each
case that is being evaluated the statements are complete.
<html>
<body>
<script language ="javascript" type="text/javascript">
var grade = 'A';
switch (grade)
{
case 'A': document.write ("Excellent");
break;
case 'B': document.write ("Good");
break;
case 'C': document.write ("Satisfactory");
break;
default: document.write("Failed");
}
</script>
</body>
</html>
If the break is missing for each case above all the values in the document.write
() will be printed on the screen.
Exercise:
1. Write a program that will display the temperature in degrees Celsius and
Fahrenheit based on user choice.
2. Continue the program given in this chapter for grade allocation for grades
between (50,60) and (60,70).
3. Write a program that will divide two numbers if the divisor is not zero.
4. Write a program that compare three inputs a, b and c and computes the
following expression (a*b) / c.
Chapter 5. Loops
Loop like conditions are a very important of programming languages. Often
they go together. The idea behind the loop is to do something repeatedly until a
situation arises to exit the process. There are three types of loops to be
considered in JavaScript and they are- While, Do-While and For.
<html>
<body>
<script language ="javascript" type="text/javascript">
var count =0;
while (count < 10)
{
document.write(count);
count = count + 1;
}
</script>
</body>
</html>
Here the output will be 0..9. The loop of counting at rate of 1 will end when
count reaches 10 and breaks the condition.
The do-while loop is similar to the while loop except that the check is done at
the end of the loop. This means that the loop will be executed at least one-time
even if the condition is false.
<html>
<body>
<script language ="javascript" type="text/javascript">
var count = 0;
do {
document.write(count);
count = count + 1;
Here the output will be 0…9 just like with the while loop. Change the count to
10 and run the code again. It will give the output 10. The condition has to be
tested has to be tested at least once.
The for loop contains three parts. First is the initialization of the loop, second
the test of the condition and then third is the iteration.
<html>
<body>
<script language ="javascript" type="text/javascript">
for(count=0;count<10;count++)
{
document.write(count);
}
</script>
</body>
</html>
There is a loop called for-in in JavaScript. This is used to deal with objects. It
will be discussed in the chapter on objects.
<html>
<body>
<script language ="javascript" type="text/javascript">
var count =0;
while (count < 10)
{
document.write(count);
count = count + 1;
if (count==5)
{
break;
}
}
</script>
</body>
</html>
The break statement will stop the count at 4 and the output will be 0…4.
The continue statement tells to immediately start the next iteration of the loop
and skip the remaining code block. At continue statement the program flow
moves to the loop check expression immediately and if the condition remains
true, the next iteration begins. If condition is false, the loop is exited.
<html>
<body>
<script language ="javascript" type="text/javascript">
var count = 0;
while (count < 10)
{
document.write(count);
count = count + 1;
if (count == 4)
{
continue;
}
}
</script>
</body>
</html>
Functions have names when they are defined. They also have parameters to be
put inside the brackets (). Thus if we have a function called test then we write
it as – test().
The brackets may contain parameters or left blank. The basic syntax for using a
function is as follows:
<html>
<body>
<script language ="javascript" type="text/javascript">
function test (parameters)
{
Statements
}
</script>
</body>
</html>
A function is called from other parts of the program by just calling its name.
Let us look at an example.
<html>
<head>
<script language ="javascript" type="text/javascript">
function first()
{
alert ("Hello World");
}
</script>
</head>
<body>
<script>
document.write(first());
</script>
</body>
</html>
Running this code will bring up a dialog box with the message Hello World.
But as soon it is closed the word undefined might be shown on the screen. This
is because this function does not have any parameters and does not return
anything. Undefined is a type in JavaScript and the sole value of this type is
Undefined value. One of the best ways to call this function would be through a
button on form. The document.write form is not able to get anything to write as
the message is in the alert box and not transferred to it.
<html>
<head>
<script language ="javascript" type="text/javascript">
function first(name)
{
var y = name;
return y;
}
</script>
</head>
<body>
<script>
var x;
x= first('John');
document.write(x);
</script>
</body>
</html>
In this example it will print the name John. Here in the function the term return,
sends back the value to the calling point for printing. Thus when having
parameters, the return will be required.
<script type="text/javascript">
var variablename = new Function(Arg1, Arg2..., "Function
Body");
</script>
The function constructor can take any number of string arguments. The last
argument is the body of the function – and can contain any relevant JavaScript
statements, separated from each other by semicolons.
The function constructor is not passed any argument that specifies a name for
the function it creates. The function created by the function constructor are
referred to as anonymous functions.
<html>
<head>
<script type="text/javascript">
var func = function(x,y){ return x*y };
function secondFunction(){
var result;
result = func(10,20);
return result;
}
</script>
</head>
<body>
<script>
var x = secondFunction();
document.write(x);
</script>
</body>
</html>
In this code there is a small change to the way document.write was used. A
variable x takes the returned value of the secondFunction and then
document.write is used to print x and not the function directly. If the function is
put between the brackets it is possible to get the correct answer but the word
undefined will follow.
Chapter 7. Events
In the last chapter functions were introduced and it could be seen that printing
them out seems to lead an undefined message. One work around was shown in
the last example and another way would be call functions through forms or
buttons. That leads to this topic.
It is perhaps the most important topic for this subject because like programs
such as Visual Basic, Visual C++, Visual J++ etc. JavaScript plays a visual
role from the user point of view. The internet is a prime example of a visual
product where buttons are pressed, files are dragged, drop down menus etc.
Thus the term events.
From the last chapter we could have called the functions from a button click.
Let us look at the most common events used on a web page.
Onload of a page:
<html>
<head>
<script type="text/javascript">
function Hello() {
document.write ("Hello World")
}
</script>
</head>
<body onLoad=Hello()>
example of onload event
</body>
</html>
This will call the function Hello and when the page has loaded it will show
Hello World. In explorer you may see the words example of onload event
before you hit allow blocked content.
Onclick event:
<html>
<head>
<script type="text/javascript">
function Hello() {
document.write ("Hello World")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="Hello()" value="Click this
button for the message">
</form>
</body>
</html>
In this example html was used to create a button and the value will give the text
shown on the button and this will call function hello to give its result. Function
Hello can be replaced by any other function.
Onsubmit:
In this event there are two parts. One part is an html form written in html and
then function that will test the contents of the html page provided. Let us look at
the html page first.
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.write("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
This is a form that asks for a name and if no name or character is entered, then
it will write the message that name has to be entered. Forms that are based on
server side languages will have to go the server for validation.
Onmouseover or onmouseout:
<html><body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">Mouse over this
text</h1>
</body></html>
In the code above the words will turn red when the mouse is over the text and
black when the mouse moves from the text.
The fact that it is a OOP language means it has characteristics such as the
following:
Objects have attributes (like characters) and methods. Objects can be user
defined. The attributes of an object in JavaScript can be of three data types or
can be other objects as well. Like the variables the attributes in the form of
variables can be used internally or all across the program (global) of the
webpage.
Methods are by which an object does something or something is done to it. The
difference between a function and a method is that -method is always tied to an
object.
The method for an object can be called by using the "this" keyword.
The new operator is used to create an instance of an object. The new operator
is followed by a constructor method. For example:
new car = new Array("Nissan","Toyota", "GM");
<html>
<head>
<title>Objects</title>
<script type="text/javascript">
var car = new Object(); // Create the object
car.make = "Nissan"; // Assign properties to the object
car.name = "Pathfinder";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
</script>
</body>
</html>
Here the Object() constructor used to define a new object and assign to it two
attributes which are make and name. They are later printed out.
<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function car(make,name){
this.make = make;
this.name = name;
}
</script>
</head>
<body>
<script type="text/javascript">
var car = new car("Nissan", "Pathfinder");
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
</script>
</body>
</html>
In the example above an object has been created using a user defined function.
This is a user defined function and the "this" keyword is used to refer to the
object.
<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function price(value){
this.price =value;
}
function car(make,name){
this.make = make;
this.name = name;
this.price = price;
}
</script>
</head>
<body>
<script type="text/javascript">
var car = new car("Nissan", "Pathfinder");
car.price(20000);
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
document.write("Car price is:" + car.price + "<br>");
</script>
</body>
</html>
Here a function price has been created followed by the car function. Object is
created from the car function and price added. The method price created first
has been added to the car function as a new property of car.
function price(value){
with this{
price =value;
}}
<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function price(value){
with (this){
price =value;
}
}
function car(make,name){
this.make = make;
this.name = name;
this.price = price;
}
</script>
</head>
<body>
<script type="text/javascript">
var car = new car("Nissan", "Pathfinder");
car.price(20000);
document.write("Car make is : " + car.make + "<br>");
document.write("Car name is : " + car.name + "<br>");
document.write("Car price is:" + car.price + "<br>");
</script>
</body>
</html>
The only change is in the function price. The programmer can choose either
style to deal with objects from functions. However, the purpose of the "with"
keyword should now be clear.
Exercise:
1. Create a function called book that has four parameters- name, author,
subject, year. Print out the values for these using an object called book.
<html>
<head>
<script type="text/javascript">
function showValue()
{
var val1 = Number.MAX_VALUE;
var val2 = Number.MIN_VALUE;
var val3 = 10;
var val4 = Number.NEGATIVE_INFINITY;
var val5 = Number.POSITIVE_INFINITY;
<html>
<head>
<title>Objects</title>
<script type="text/javascript">
function car(make,name){
this.make = make;
this.name = name;
}
</script>
</head>
<body>
<script type="text/javascript">
var mycar = new car("Nissan", "Pathfinder");
car.prototype.price=null;
mycar.price= 20000;
document.write("Car make is : " + mycar.make + "<br>");
document.write("Car name is : " + mycar.name + "<br>");
document.write("Car price is:" + mycar.price + "<br>");
</script>
</body>
</html>
Here we are adding a new property to the object using a number property
called prototype. The code is the same as that objects in the previous chapter.
The difference is the prototype keyword used to introduce a new property
price into the object car referenced by mycar and then we add the value later to
print out the result.
<html>
<body>
<script type="text/javascript">
var num = new Number(123);
document.write("num.constructor() is : " +
num.constructor);
</script></body></html>
It will return an output: num.constructor() is : function Number() { [native
code] }
Number object has properties as seen so far and therefore like objects it has
methods also. They are:
toFixed() - formats a number with a specific number of digits to the right of the
decimal point
<html>
<head>
<title>Javascript Methods</title>
</head>
<body>
<script type="text/javascript">
var num=123.5678;
var val = num.toExponential();
document.write("num.toExponential() is : " + val );
document.write("<br />");
val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");
val = num.toFixed();
document.write("to_fixed : " + val );
document.write("<br />");
val = num.toFixed(2);
document.write("to_fixed : " + val );
document.write("<br />");
</script>
</body>
</html>
num.toExponential() is : 1.235678e+2
num.toExponential(4) is : 1.2357e+2
to_fixed : 124
to_fixed : 123.57
It should be noticed the difference between first line and second line is the
precision after the decimal point and the same case for lines three and four.
<html>
<head>
<title>Javascript Methods</title>
</head>
<body>
<script type="text/javascript">
var num=123.5678;
var val = num.toLocaleString();
document.write("num.toLocaleString is : " + val );
document.write("<br />");
var val = num.toPrecision(3);
document.write("num.toPrecision is : " + val );
document.write("<br />");
var val = num.toString();
document.write("num.toString is : " + val );
document.write("<br />");
var val = num.valueOf();
document.write("num.valueOf() is : " + val );
document.write("<br />");
</script>
</body>
</html>
num.toLocaleString is : 123.568
num.toPrecision is : 124
num.toString is : 123.5678
num.valueOf() is : 123.5678
Chapter 10. Boolean
Boolean object has the following properties:
Constructor - Returns reference to the Boolean function that created the object.
<html>
<head>
<title>JavaScript constructor() </title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is : " +
bool.constructor);
</script>
</body>
</html>
The output of this code will be similar to the constructor method output for
number objects and is as follows:
toString() - gives either true or false according to the state of the object.
valueOf () - gives the primitive value of the Boolean object.
<html>
<head>
<title>Boolean Methods</title>
</head>
<body>
<script type="text/javascript">
function car(make,name)
{
this.make = make;
this.name = name;
}
var mycar = new car("Nissan","Pathfinder");
var x = new Boolean(true);
document.write("mycar.toSource() is : " +
mycar.toSource());
document.write("x.toString() is : "+ x.toString() + "<br>");
document.write( "x.valueOf is : " + x.valueOf() + "<br>");
</script>
</body>
</html>
({Make:"Nissan", Name:"Pathfinder"})
x.toString() is : true
x.valueOf is : true
Chapter 11. Strings
The string object can be initiated as follows:
Constructor – gives a reference to the string function which created the object
<html>
<head>
<title>String length</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "Hello, this is how to find the length
of a string." );
document.write("str.length is:" + str.length + "<br>");
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
Here the output would be fifty (50) for the length of the string and similar to
constructor outputs for number and string will be as follows:
str.length is: 50
str.constructor is:function String() { [native code] }
String methods (not exhaustive) are as follows
IndexOf() – gives the index within the calling String object for the first
occurrence of a specified value.
<html>
<head>
<title>String methods</title>
</head>
<body>
<script type="text/javascript">
var val = new String("Hello these are some of the methods
related to a string.");
var index = val.indexOf( "are" );
document.write("val.charAt(0):" + val.charAt(0) + "
<br>");
document.write("val.charAt(2):" + val.charAt(2) + "
<br>");
document.write("val.charCodeAt(3) is:" +
val.charCodeAt(3) + "<br>");
document.write("indexOf found String :" + index );
</script>
</body>
</html>
Here we see the use of three methods- charAt(), charCodeAt() and indexOf().
The output will look as follows:
val.charAt(0):H
val.charAt(2):l
val.charCodeAt(3) is:108
indexOf found String :12
Let us look some more examples of string methods:
<html>
<title>String Methods</title>
</head>
<body>
<script type="text/javascript">
var val = "Welcome to string methods.";
var result = val.split(" ", 3);
document.write( val + "<br>" );
var sliced = val.slice(3, -2);
document.write( sliced + "<br>" );
var val2 = val.search("th");
document.write(val2 + "<br>" );
var val3= ".";
<html>
<title>String Methods</title>
</head>
<body>
<script type="text/javascript">
var val = "Welcome to string methods.";
document.write("(1,2): " + val.substr(1,9) + "<br>");
document.write(val.toLowerCase( ) + "<br>");
document.write(val.toUpperCase( ) + "<br>");
var index = val.localeCompare( "XYZ" );
document.write("localeCompare first :" + index );
</script>
</body>
</html>
(1,2): elcome to
welcome to string methods.
WELCOME TO STRING METHODS.
localeCompare first :-1
There are some string methods that return a copy of the string enclosed within a
html tag. They are as follows:
<html>
<body>
<script type="text/javascript">
var val = new String("String methods");
document.write(val.big() + "<br>");
document.write(val.anchor()+ "<br>");
document.write(val.fontcolor("blue")+ "<br>");
document.write(val.bold() + "<br>");
document.write(val.fontsize(7) + "<br>");
</script>
</body>
</html>
Instead of document.write try alert() and see if the result looks different. Say
for example type alert(val.bold());
In a similar way try out the rest of the methods shown above.
Chapter 12. Arrays
An array stores multiple data of the same type in the form rows and columns.
Yes, like a matrix in math.
In an array the first element is given the index 0. So the above is an array of
size 3 but numbered from 0 through 2.
Constructor - gives a reference to the array function that created the object.
<html>
<body>
<script type="text/javascript">
var car = new Array( "Nissan", "Toyota", "GM" );
document.write("car.constructor is:" + car.constructor + "
<br>");
document.write("car.length is:" + car.length + "<br>");
</script>
</body>
</html>
The output will be as follows:
filter() - creates a new array with all the elements of existing array for which
the filtering function holds true.
indexOf() - Gives the first least index of an element in the array equal to a
given value or -1 if none is found.
lastIndexOf() - gives the last greatest index of an element within the array
equal to the given value or -1 if none is found.
map() - gives a new array with the results of calling a function on every
element of the array.
pop() - deletes the last element from an array and returns the element.
push() - adds an element to the end of an array and gives the length of the array.
reduce() - apply a function on two values of the array at the same time to
reduce it to a single value
reduceRight() - apply a function on two values of the array from right to left to
reduce it to a single value.
shift() - removes the first element from an array and returns that element.
some() - gives true if at least one element in the array satisfies a testing
function.
unshift()- adds one or more elements to the front of an array and returns the
new length of the array.
<html>
<head>
<title>Array Methods</title>
</head>
<body>
<script type="text/javascript">
var car = ["Nissan", "Toyota", "GM"];
var car2 = ["Hyundai","VW","Suzuki"];
var carlist = car.concat(car2);
document.write("carlist : " + carlist + "<br>");
var val = "Mazda";
document.write(" New carlist has : " + carlist.push(val) +
"<br>");
document.write("and the new carlist : " + carlist.reverse()
+ "<br>");
</script>
</body>
</html>
The above code demonstrates the concat, push and reverse methods. First two
lists are added together. The size of the two arrays are not important in this
case as the new list is being appended to the first list. We are adding a new
element and that will go to the end of the list and finally the list is being printed
in a reverse manner.
carlist : Nissan,Toyota,GM,Hyundai,VW,Suzuki
New carlist has : 7
and the new carlist : Nissan,Toyota,GM,Hyundai,VW,Suzuki,Mazda
and the new carlist in reverse order is :
Mazda,Suzuki,VW,Hyundai,GM,Toyota,Nissan
<html>
<head>
<title>Array Methods</title>
</head>
<body>
<script type="text/javascript">
var index = [12, 5, 8, 130, 44];
document.write("sort is : " + index.sort() + "<br>" );
document.write("index is : " + index.lastIndexOf(8) + "
<br>" );
document.write("slice at index 2" + index.slice(2) + "
<br>" );
document.write("splice at index 2 : " + index.splice(2) + "
<br>" );
document.write("shift : " + index.shift() + "<br>" );
</script>
</body>
</html>
The methods shown above are sort, lastIndexOf, slice, splice and shift and the
output will look as follows:
sort is : 12,130,44,5,8
index is : 4
slice at index 244,5,8
splice at index 2 : 44,5,8
shift : 12
The two are related in terms of what they do. The difference is the direction.
Let us take an example of three numbers 100, 2 and 25 in an array.
So in the case of reduce the direction is from left to right and the opposite
(right to left) for reduceRight.
<html>
<head>
<script language="JavaScript">
var answer = [100,2,25].reduceRight(function(a, b){ return
a / b; });
document.write("The answer is : " + answer);
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script language="JavaScript">
var total = [100,2,25].reduce(function(a, b){ return a / b;
});
document.write("total is : " + total );
</script>
</head>
<body>
</body>
</html>
The code is the same except for the reduce instead of reduceRight.
When a date object is created with new Date() without anything in the brackets
then the date object is set the current date and time on the system.
Milliseconds: Placing 10000 within the brackets creates a date that represents
ten seconds past midnight on 1/1/70.
Datestring: a string representation of the date, in the format accepted by the
Date.parse() method will be taken as the value of the object.
Arguments: The date object can take several other arguments inside the bracket
such as:
year: Integer value representing the year in full format. Ex: 2017
month: Integer value representing the month, beginning with 0 for January.
date: Integer value representing the day of the month.
hour: Integer value representing the hour of the day in 24-hour format.
minute: Integer value representing the minute segment of a time reading.
second: Integer value representing the second segment of a time reading.
millisecond: Integer value representing the millisecond segment of a time
reading.
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
This will give the setting on the system on which the browser is open.
getMinutes() - returns the minutes based on the system date and time.
getMonth() - returns the month based on the system date and time.
getSeconds() - returns the seconds based on the system date and time.
getTime() - returns the numeric value of the specified date as the number of
milliseconds since January 1, 1970.
getUTCDate() - returns the day (date) of the month in the specified date
according to universal time.
getUTCDay() - returns the day of the week in the specified date according to
universal time.
SetDate() - sets the day of the month for a specified date according to local
time.
setFullYear() - sets the full year for a specified date according to local time.
setHours() - sets the hours for a specified date according to local time.
setMinutes() - sets the minutes for a specified date according to local time.
setMonth() - sets the month for a specified date according to local time.
setSeconds() - sets the seconds for a specified date according to local time.
setUTCDate() - sets the day of the month for a specified date according to
universal time.
setUTCHours() - sets the hour for a specified date according to universal time.
<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
document.write("getDate() : " + val.getDate() + "<br>" );
document.write("getDay() : " + val.getDay() + "<br>");
document.write("getFullYear() : " + val.getFullYear() + "
<br>");
document.write("getHours() : " + val.getHours()+ "<br>");
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
document.write("getDate() : " + val.getDate() + "<br>" );
document.write("getDay() : " + val.getDay() + "<br>");
document.write("getFullYear() : " + val.getFullYear() + "
<br>");
document.write("getHours() : " + val.getHours()+ "<br>");
document.write("getMilliseconds() : " +
val.getMilliseconds() + "<br>");
document.write("getMinutes() : " + val.getMinutes() + "
<br>" );
document.write("getMonth() : " + val.getMonth() + "
<br>");
document.write("getSeconds() : " + val.getSeconds() + "
<br>");
document.write("getTime() : " + val.getTime() + "<br>");
document.write("getTimezoneOffset() : " +
val.getTimezoneOffset() + "<br>");
</script>
</body>
</html>
getDate() : 25
getDay() : 0
getFullYear() : 2016
getHours() : 22
getMilliseconds() : 0
getMinutes() : 10
getMonth() : 11
getSeconds() : 0
getTime() : 1482693000000
getTimezoneOffset() : -180
Now let us look at some further examples with some of the other methods
mentioned earlier for date object.
<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
document.write("getUTCDate() : " + val.getUTCDate() + "
<br>" );
document.write("getUTCDay() : " + val.getUTCDay() + "
<br>" );
document.write("getUTCFullYear() : " +
val.getUTCFullYear() + "<br>");
document.write("getUTCHours() : " + val.getUTCHours()
+ "<br>" );
document.write("getUTCMilliseconds() : " +
val.getUTCMilliseconds() + "<br>");
document.write("getUTCMinutes() : " +
val.getUTCMinutes() + "<br>" );
document.write("getUTCMonth() : " + val.getUTCMonth()
+ "<br>");
document.write("getUTCSeconds() : " +
val.getUTCSeconds() + "<br>");
document.write("getYear() : " + val.getYear() + "<br>");
</script>
</body>
</html>
getUTCDate() : 25
getUTCDay() : 0
getUTCFullYear() : 2016
getUTCHours() : 19
getUTCMilliseconds() : 0
getUTCMinutes() : 10
getUTCMonth() : 11
getUTCSeconds() : 0
getYear() : 116
Let us look at some more examples of methods related to the date object.
Here in the examples there are two variables val and val2. The first is set to a
particular date and the second is kept open to the date on the system. Note the
results for both cases.
<html>
<body>
<script type="text/javascript">
var val = new Date("December 25, 2016 22:10:00");
var val2 = new Date();
val.setDate( 24 );
val2.setDate( 24 );
document.write( val + "<br>");
document.write( val2 + "<br>");
val.setFullYear( 2014 );
document.write( val + "<br>" );
val.setHours( 02 );
document.write( val + "<br>" );
val2.setMonth( 2 );
document.write( val2 + "<br>");
val2.setUTCDate( 20 );
document.write( val2 + "<br>" );
</script>
</body>
</html>
In addition to the methods mentioned above the date object has two static
methods:
Date.parse() - Parses a string representation of a date and time and returns the
internal millisecond representation of that date.
Date.UTC() - Returns the millisecond representation of the specified UTC date
and time.
Let us look at an example:
<html>
<head>
<title>Date parse Method</title>
</head>
<body>
<script type="text/javascript">
var val = Date.parse( "Feb 15, 2017 23:30:00" );
document.write( "Number of milliseconds from 1970: " +
val );
</script>
</body>
</html>
Now suppose we want to use the second method Date.UTC(). Here the year
will be in full format, month (0-11), day (1-31), hours (0-23), minutes(0,59),
seconds (0,59) and milliseconds (0,999). Let us look at an example.
<html>
<head>
<title>Date parse Method</title>
</head>
<body>
<script>
var val = Date.UTC(2016,2,15);
document.write( "Number of milliseconds from 1970: " +
val );
</script>
</body>
</html>
The output will be as follows:
The year in this example is 2016, the month February and the day 15.
Chapter 14. Actions in Math
The math object was discussed before with respect to its properties and
methods. Here we look at some more useful properties and methods using math
in JavaScript.
Euler - E
<html>
<body>
<script type="text/javascript">
var val = Math.E;
document.write("Property Value is :" + val + "<br>");
var val = Math.LN2;
document.write("Property Value is :" + val + "<br>");
var val = Math.LOG10E;
document.write("Property Value is :" + val + "<br>");
var val = Math.PI;
document.write("Property Value is :" + val + "<br>");
var val = Math.SQRT2;
document.write("Property Value is :" + val + "<br>");
</script></body></html>
The output will be as follows:
exp() - gives the value when N is the argument and E is the Euler's constant.
floor() - gives the largest integer less than or equal to a number.
max() - gives the maximum number after comparing two or more numbers.
min() - gives the minimum number after comparing two or more numbers.
<html><body><script>
var val = Math.abs(-20);
document.write("abs() is:" + val + "<br>");
var val = Math.sqrt(20);
document.write("sqrt() is:" + val + "<br>");
var val = Math.sin(90);
document.write("sin() is:" + val + "<br>");
var val = Math.ceil(20.145);
document.write("ciel() is:" + val + "<br>");
var val = Math.exp(20);
document.write("floor() is:" + val + "<br>");
var val = Math.max(10,20,25,15,12,14,35,8);
document.write("max() is:" + val + "<br>");
var val = Math.pow(10,2);
document.write("pow() is:" + val + "<br>");
var val =Math.random();
document.write("random() is:" + val + "<br>");
var val = Math.round(20.541);
document.write("round() is:" + val + "<br>");
</script></body></html>
A pattern is a string that specifies the pattern of the regular expression that is of
interest. Attributes are optional strings that specifies some global or multi line
matches.
Regular expressions are often seen in the form of brackets, alphabets, / or *.
Brackets have the following meaning:
[...] = Any one character between the brackets.
[^..] = Any one character not between the brackets.
[0-9] = Must be a number from 0 through 9 both being inclusive.
[a-z] = Matches any lower characters a through z.
[A-Z] = Matches any upper characters A through Z.
[a-Z] = Matches any character from lower case a through upper case Z.
While these are supersets within the brackets lower ranges can be mentioned.
For example, [0-1].
Further we have the following:
p+ = matches anything which has at least one p.
p* = matches a string which has zero or more p's.
p? = matches a string with one or more p's.
p{N} = matches any string that has a sequence of N p's.
p{3,5} = matches any string that has a sequence of three or five p's.
p{3, } = matches any string that has a sequence of at least three p's.
p($) = matches any string that has a p at the end of it.
^p = matches any string with p at the start.
. = single character.
\s = a whitespace character.
\D = not a digit.
[\b] = backspace.
g = finds all matches and does not stop after finding the first match.
<html><body><script type="text/javascript">
var val = new RegExp( "This is a regular expression." );
document.write(val.global + "<br>");
val = new RegExp(val, "g" );
document.write(val.global + "<br>");
val =new RegExp(val,"i");
document.write(val.ignoreCase + "<br>"); <script>
</body></html>
The output of the above code will be as follows:
false
true
true
RegExp.exec() and RegExp.test() methods work only if the g modifier has been
set. The lastIndex is a read write property.
<html>
<body>
<script type="text/javascript">
var val = "This is an example of a regular expression
method.";
var x = new RegExp( "example", "g" );
x.test(val);
document.write("Current Index: " + x.lastIndex + "<br>");
x.test(val);
document.write("Current Index: " + x.lastIndex + "<br>");
</script>
</body>
</html>
There is a built in JavaScript feature called auto refresh which can be called
by using setTimeout(). This will auto refresh the page after a certain interval in
seconds which have to be added to that function.
<html>
<head>
<script type="text/JavaScript">
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
</script>
</head>
<body onload="JavaScript:AutoRefresh(5000);">
<img src=test.jpg>
<p>This page will refresh every 5 seconds. </p>
</body>
</html>
Here test.jpg was a picture to test if the page reloads every five seconds.
The ‘t’ indicates the auto refresh is from the server side versus client side in
the form of the cache. If the latter is the intention, then replace ‘t’ with ‘f’.
This kind of auto refreshing is only good for those webpages which have
content that is either live or changing at a fast pace. For most websites having
this feature in an opening page may not be practical.
<html>
<head>
<script type="text/javascript">
function rd() {
window.location="http://www.xyz.com";
}
</script>
</head>
<body>
<p>Click the following button, you will be redirected to
our new home page.</p>
<form>
<input type="button" value="Redirect Me" onclick="rd();"
/>
</form>
</body>
</html>
This will create a page with a button that needs to be clicked for redirection to
take place. The page will remain static until the button is pressed. It might be
more impressionable if in addition to providing a button to click the page
reloads the new website after a few seconds. The setTimeout() method in the
previous example could be used for this purpose.
<html>
<head>
<script type="text/javascript">
function rd() {
window.location="http://www.xyz.com";
}
document.write ("You will be redirected to our main page
in 5 seconds!");
setTimeout('rd()', 5000);
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function Hello() {
alert ("This is a dialog box");
document.write ("Hello how are you??");
}
</script>
</head>
<body>
<p>Click the following button:</p>
<form>
<input type="button" value="Click Me" onclick="Hello();"
/>
</form>
</body>
</html>
In the program after the dialog box is shown the body of the page will show the
words “Hello how are you?”. The alert() by itself was sufficient to pass the
message but what happens after the dialog box is closed? Thus when using a
dialog box with a button as in this case do not forget the body of the page needs
to have something meaningful.
<html>
<head>
<script type="text/javascript">
function gc(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
window.location="http://www.xyz.com";
return true;
}else{
return false;
}
}
</script>
</head>
<body>
<p>Click the following button: </p>
<form>
<input type="button" value="Click Me" onclick="gc();" />
</form>
</body>
</html>
Here the dialog box gives two options. If “OK” it will continue to open a page
in the program otherwise it will remain on the same page. The prompt() feature
in JavaScript allows one to enter a value into the dialog box as an input.
<html>
<head>
<script type="text/javascript">
function gv(){
var val = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + val);
}
</script>
</head>
<body>
<p>Click the following button: </p>
<form>
<input type="button" value="Click Me" onclick="gv();" />
</form>
</body>
</html>
The input box will appear after clicking the button and whatever is provided
by the user will be printed to the body of the page. The usefulness of this
method is left to the reader. Normally input in a form of a website is sent to the
server for processing.
Chapter 17. Cookies
Cookies are connected with the word sessions in internet programming.
Sessions are not part of JavaScript but other programming languages or scripts
used for making internet pages.
Cookies are text files that store some data perceived to be important from the
point of view of the server and the client.
Expires – tells when the cookie will expire. Leaving it blank means that cookie
will last only during the browser session of the user.
Path – The path to the web page that set the cookie. This could be left blank.
Name=Value – cookies are set and retrieved in the form of key value pairs.
<html>
<head>
<script type="text/javascript">
document.cookie ="cookie=" + escape("This is my first
cookie");
alert(document.cookie);
</script>
</head>
</html>
The above code creates a basic cookie. Here we are trying to display the
cookie with an alert dialog box.
The output will look like this when seen in Microsoft IE Edge.
Now let us look into a way to access the cookie. We start with the
document.cookie statement as follows:
Use the split() method defined in the chapter on strings and do this:
One can guess after the name we need a value for the cookie as we discussed
in the beginning of the chapter. Thus the next cookie part is:
The first script had given the name of the cookie as cookie and value as my
first cookies which has now been found and displayed.
Cookies expire at the end of the browser session. If a cookie needs to be active
beyond that the expiry date needs to be included. For this purpose, let us first
create a variable for our date of expiry for the cookie.
var cdate = new Date(2017, 5,7,12,00,00); (The date of expiry here is 7th of
May at midday in the year 2017)
Like it was done in the first code for naming the cookie:
<html>
<head>
<script type="text/javascript">
var cdate = new Date(2017,5,7,12,00,00);
document.cookie ="cookie=" + escape("This is my first
cookie") + ";expires=" + cdate.toGMTString();
alert("cookie=" + escape("This is my first cookie") +
";expires=" + cdate.toGMTString());
</script>
</head>
</html>
<html>
<head>
<script type="text/javascript">
var cdate = new Date();
cdate.setTime(cdate.getTime() - 86400000);
document.cookie ="cookie=" + escape("This is my first
cookie") + ";expires=" + cdate.toGMTString();
alert("cookie=" + escape("This is my first cookie") +
";expires=" + cdate.toGMTString());
</script></head></html>
The date of the cookie is kept to a past date. The number 86400000 represents
1 day in milliseconds.
<html>
<head>
<script type="text/javascript">
document.cookie ="cookie1=" + escape("This is my first
cookie");
document.cookie ="cookie2=" + escape("This is my second
cookie");
var first = document.cookie.indexOf("cookie1=");
var firstEnd = document.cookie.indexOf(";", first + 1);
if (firstEnd == -1) { firstEnd = document.cookie.length; }
var firstCookie =
unescape(document.cookie.substring(first+8,firstEnd));
var second = document.cookie.indexOf("cookie2=");
var secondEnd = document.cookie.indexOf(";", second + 1);
if (secondEnd == -1) { secondEnd =
document.cookie.length;}
var secondCookie =
unescape(document.cookie.substring(second+8,secondEnd));
alert(firstCookie);
alert(secondCookie);
</script>
</head>
</html>
The last two alerts will show the cookies separately. Creating two cookies is
similar to making each cookie as seen earlier. Accessing the cookies is where
the difference lies. To access each cookie, the indexOf method is used to find
where the cookie ends.
Check to see whether or not a semicolon was found by checking if firstEnd has
the value -1. If the value is -1, it means that this cookie is the last cookie and
firstEnd should be set to the last character in the document.cookie string.
Extract the value of the first cookie by taking the substring starting at the
character after "cookie1=" and ending at the semicolon. This is done with the
substring method of the String object, and the resulting substring is passed to
unescape to remove any escaped characters. The results are stored in the
variable firstCookie.
Note that first + is used as the first character of the substring;this represents the
first character after the equal sign after cookie1 (since "cookie1=" is 8
characters long).
The same process is repeated for the second cookie as shown in the code
above.
In this code a cookie called cookie3 is being searched for. If it exists, then fine
but if it does not then it is assumed that user has not visited the page before and
the user is send to another page. The purpose of this type of a redirection is
that some websites might require a user to register before continuing to browse
through their website.
The line if (firstVisit == -1) { } tests whether the cookie mentioned exists or
not.
Chapter 18. DHTML
Throughout the codes in this book we have used html along with
document.write to manipulate the output.
<html>
<head>
<script language="JavaScript">
var placeholder =
window.open("holder.html","placeholder","width=200,height=200");
</script>
<title>The Main Page</title>
</head>
<body onLoad="placeholder.close()">
<p>This is the main page</p>
</body>
</html>
In this script we are trying to create a 200 by 200-pixel notice saying the page
is loading before the main page is displayed. To do this two html files are
required. One for the loading message and one for the main page. The
JavaScript above is included in the html file containing the main content. Size
of the message can be changed. This kind of method could be used to send
other notice messages of relevance to the page. Both files are assumed to be in
the same directory. Also window has to be closed once opened.
Now let us create a form using JavaScript. The code will look like this.
<html>
<body>
<form method="post" action="target.html"
name="thisForm">
<input type="text" name="myText">
<select name="mySelect">
<option value="1">Link one</option>
<option value="2">Link two</option>
</select>
<br><input type="submit" value="Submit Me"></form>
</body></html>
You will get a selection of two links and the output will look like this.
Here the target link for the action in the form definition is an html file.
Normally it will be a file in a scripting language such as php or asp etc.
To access text in a text box in a form done in html you may use the following
code.
<html>
<body>
<form name="myForm">
<input type="text" name="myText">
</form>
<a href="#"
onClick="window.alert(document.myForm.myText.value);">Check
Text Field</a>
</body></html>
So if I type hello in the text box the output message from the alert will be hello
as seen below.
To copy text from one text field to the other look at the following code.
<html><body>
<form name="myForm">
Enter some Text: <input type="text" name="myText"><br>
Copy Text: <input type="text" name="copyText">
</form><a href="#"
onClick="document.myForm.copyText.value =
document.myForm.myText.value;">Copy Text Field</a>
</body></html>
This will give the following output.
<html>
<body>
<form name="myForm">
Enter some Text: <input type="text" name="myText"
onChange="window.alert(this.value);">
</form>
</body></html>
<html>
<body>
<form name="myForm">
<select name="mySelect">
<option value="Link one">1</option>
<option value="Link two">2</option>
<option value="Link three">3</option>
</select>
</form>
<a href="#"
onClick="window.alert(document.myForm.mySelect.value);">Check
Selection List</a
</body></html>
<html>
<body>
<script>
function list(list) {
list.length = 3;
list.options[0].text = "Link 1";
list.options[0].value = " Link Value 1";
list.options[1].text = "Link 2";
The following code will allow user to select from a given list and see the
selection as an alert dialog box.
<html><body>
<form name="myForm">
<select name="mySelect"
onChange="window.alert(this.value);">
<option value="First Choice">1</option>
<option value="Second Choice">2</option>
<option value="Third Choice">3</option>
</select></form> </body></html>
The output of the previous code is shown below the table. Another form
element is the radio button. In the following code JavaScript is used to access
the radio button selected.
<html>
<body>
<script language="JavaScript">
function Button() {
var buttonValue = "";
for (i = 0; i < document.myForm.myRadio.length; i++) {
if (document.myForm.myRadio[i].checked) {
buttonValue = document.myForm.myRadio[i].value;
}
}
return buttonValue;
}
</script>
<form name="myForm">
<input type="radio" name="myRadio"
value="First Button"> Button 1<br>
<input type="radio" name="myRadio"
value="Second Button"> Button 2
</form>
<a href="#" onClick="window.alert(Button());">Which
Radio Button?</a>
</body></html>
Clicking radio button 2 will give second button. The code below will detect
the radio button clicked.
<html>
<body>
<form name="myForm">
<input type="radio" name="myRadio" value="First
Button" onClick="window.alert('First Button
selected');">Button 1<br>
<input type="radio" name="myRadio" value="Second
Button" onClick="window.alert('Second Button
selected');">Button 2
</form>
</body></html>
The following code can be used to detect the clicking of a checkbox on a form.
<html>
<body>
<form name="myForm">
<input type="checkbox" name="myCheck"
value="My Check Box"> Check Me
</form>
<a href="#"
onClick="window.alert(document.myForm.myCheck.checked
? 'Yes' : 'No');">Am I Checked?</a>
</body></html>
The following code demonstrates how a choice can be changed with respect to
a check box.
<html>
<body>
<form name="myForm">
<input type="checkbox" name="myCheck"
value="My Check Box"> Check Me
</form>
<a href="#"
onClick="document.myForm.myCheck.checked =
false;">Uncheck the box</a>
</body></html>
Clicking on the uncheck the box link will change the selection from yes to no. It
is a very common feature of a form to have text boxes. To make each text box
whose info is required to be mandatory one could use the following type of
code to indicate that the text box is empty.
<html><body>
<script language="JavaScript">
function checkField(field) {
if (field.value == "") {
window.alert("You must enter a value in the field");
field.focus();
}}
</script>
<form name="myForm" action="target.html">
Text Field: <input type="text" name="myField"
onBlur="checkField(this)"><br>
<input type="submit">
</form></body></html>
The output will look as follows.
The other alternative is to wait till one clicks the submit button to check if the
needed text boxes are filled up.
<html>
<head>
<script language="JavaScript">
function check(formObj) {
var fk= true;
if (formObj.myField.value == "") {
window.alert("You must enter a value in the field");
formObj.myField.focus();
fk = false;
}
return fk;
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return check(this);">
Text Field: <input type="text" name="myField"><br>
<input type="submit">
</form>
</body></html>
In this code function is called on clicking the button and is attached to the
onSubmit part of the form action. The check function can also be added to the
onClick event of the button itself like this.
One of the common features of a form such as an online application form is the
query on a phone number. Phone numbers come in different formats across the
globe. Let us look at the following code.
<html>
<head>
<script language="JavaScript">
function checkForm(formObj) {
return checkPhone(formObj.myField.value); }
function checkPhone(phone) {
if (phone.length == 0) {
window.alert("You must provide a phone number.");
return false;
}
phone = phone.replace("-","");
phone = phone.replace(" ","");
phone = phone.replace("(","");
phone = phone.replace(")","");
phone = phone.replace(".","");
if (phone.length != 10) {
window.alert("Phone numbers must only include a 3-digit
area code and a 7-digit phone number.");
return false;
}
for (i=0; i<phone.length; i++) {
if (phone.charAt(i) < "0" || phone.charAt(i) > "9") {
window.alert("Phone numbers must only contain
numbers.");
return false;
}
}
return true;
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return checkForm(this);">
Phone: <input type="text" name="myField"><br>
<input type="submit">
</form>
</body></html>
Now with this code if a phone number is not entered or not in the right format
the error message will come up accordingly. This code is long. Another way
phone can be verified is by using regular expressions. As mentioned in the
regular expressions chapter the first thing to do is to create a pattern to test.
Using regular expressions can significantly decrease coding. To use regular
expressions, the following has to be done:
<html><head>
<script language="JavaScript">
function checkForm(formObj) {
return checkPhone(formObj.myField.value); }
function checkPhone(phone) {
var check = /^\({0,1}[0-9]{3}\){0,1}[ \-\.]{0,1}[0-9]{3}[
\-\.]{0,1}[0-9]{4}$/;
if (!check.test(phone)) {
window.alert("Provide a valid phone number.");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return checkForm(this);">
Phone: <input type="text" name="myField"><br>
<input type="submit">
</form>
</body></html>
<html>
<head>
<script language="JavaScript">
function checkForm(formObj) {
return Password(formObj.myPassword.value,
formObj.myConfirm.value);
}
function Password(password,confirm) {
if (password != confirm) {
window.alert("Passwords don’t match.");
return false;
}
if (password.length < 8) {
window.alert("Passwords must be 8 or more characters");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="target.html"
onSubmit="return checkForm(this);">
Enter Password: <input type="password"
name="myPassword"><br>
Confirm Password: <input type="password"
name="myConfirm"><br>
<input type="submit">
</form>
</body></html>
The output will look as follows if a wrong confirmation is given or not given.
Chapter 19. Browser Windows
To put a message in the status bar of the browser use the following code.
<html>
<head>
<script language="JavaScript">
window.status
</script>
</head>
<body>
<script language="JavaScript">
window.status = "A new status message";
</script>
</body>
</html>
<html>
<head>
</head>
<body>
<script language="JavaScript">
var userChoice = window.confirm("Click OK or Cancel");
if (userChoice) {
document.write("You chose OK");
} else {
document.write("You chose Cancel");
}
</script>
</body>
</html>
<html>
<head>
</head>
<body>
<script language="JavaScript">
var userName = window.prompt("Please Enter Your
Name","Enter Your Name Here");
document.write("Your Name is " + userName);
</script>
</body>
</html>
To open a particular page in a browser use windows.open("url") within script
tags similar to the code below.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow");
</script>
</body>
</html>
The following code allows to control the height and width of the new browser
window that is opened to load a page.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","height=300,
width=500");
</script>
</body>
</html>
The following code allows to control the location where the new browser
window will open. The only additional code is the x and y coordinates and the
distance in pixels from the top.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","height=300,
width=500, screenx =600, screeny = 800, top= 300");
</script>
</body>
</html>
The following code allows the toolbars to be seen in the new window opened
to load a page. Setting toolbar = no will hide the toolbar of the browser.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","toolbar=yes");
</script>
</body>
</html>
The following code allows for the control of scroll bars in the new window
opened for a page.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","scrollbars=yes",
"height=300, width=300");
</script>
</body>
</html>
The following code allows for the new window opened to load a page to be
resizable.
<html>
<head>
</head>
<body>
<script language="JavaScript">
window.open("http://www.xyz.org/","mynewwindow","resizable=yes,
height=300, width=300");
</script>
</body>
</html>
Setting the value of resizable to no will make the page non expandable. A
window can be closed by using the window.close() feature of JavaScript. Add
this after the window.open statement above and see the result.
Chapter 20. Moving Objects
Objects have been mentioned and discussed in a previous chapter. Objects are
referenced in JavaScript by using the document.getElementById method. Each
object that needs to be used will require an ID using the id attribute of the
element’s tag.
<html>
<head>
<script language="JavaScript">
function space(objectID) {
var val = document.getElementById(objectID);
val.style.lineHeight = parseInt(val.style.lineHeight) + 25 +
"px";
}
</script>
</head>
<body>
<div id="myspace"style="position: absolute; left: 100px;
top: 50px; width: 300px; font-size: 14px; line-height: 18px;
background-color: #cccccc;">Increasing line spacing for
this text. This is the second line. This is the third line. This
is the fourth line.</div>
<a href="javascript:space('myspace');">Increase line
spacing.</a>
</body>
</html>
The output of this code to increase space between the lines will look as
follows.
In the above code the line spacing will increase with each click of the link.
The link can also be made as a button.
In the following code the same technique as above to get the location of an
object. A function loc calls on an object and a variable val is used to reference
the object. Location details are obtained from val.style statement. The object of
interest is passed on to the function to get the results.
<html>
<head>
<script language="JavaScript">
function loc(objectID) {
var val = document.getElementById(objectID);
var x = val.style.left;
var y = val.style.top;
window.alert("Location: (" + x + "," + y + ")");
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:loc('myspace');">Where is the object?
</a>
</body>
</html>
<html>
<head>
<script language="JavaScript">
function loc(objectID) {
var val = document.getElementById(objectID);
val.style.left = 500;
val.style.top = 200;
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:loc('myspace');">Move the object to
500,200 location</a>
</body>
</html>
In the code above the object has moved both along x and y axis. If only
horizontal movement is required, then the statement val.style.top need not be
included. Similarly, if only vertical movement is only required then the
val.style.left statement need not be included.
It is possible to create buttons that call upon functions to move horizontally or
vertically.
The following code will keep the object in the horizontal center.
<html>
<head>
<script language="JavaScript">
function hz(objectID) {
var val = document.getElementById(objectID);
var width = document.body.clientWidth
var objectWidth = val.style.width;
var loc = (width - objectWidth) / 2;
val.style.left = loc;
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:hz('myspace');">Move the object to
horizontal center.</a>
</body>
</html>
An object can be kept vertically centered by using the same above code by
changing the var width to:
The code will look like the one in the table below.
<html>
<head>
<script language="JavaScript">
function hz(objectID) {
var val = document.getElementById(objectID);
var height = document.body.clientHeight
var objectHeight = val.style.height;
var loc = (height - objectHeight) / 2;
val.style.top = loc;
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:hz('myspace');">Move the object to
vertical center.</a>
</body>
</html>
The follow code allows to hide an object. The structure of the code is similar
to the code written above in the chapter.
<html>
<head>
<script language="JavaScript">
function hz(objectID) {
var val = document.getElementById(objectID);
val.style.visibility="hidden";
}
</script>
</head>
<body>
<div id="myspace" style="position: absolute; left: 100px;
top: 90px; background-color: #ffffff;">The object of
interest.</div>
<a href="javascript:hz('myspace');">Hiding an object.</a>
</body>
</html>
The object will now be hidden on clicking the link. The key term above is the
style.visibility statement . If it is set to hidden the object will not be visible.
The opposite is visible.
The following code will give color depth of the monitor being used to observe
the result of code.
<html>
<head>
<script language="JavaScript">
var depth = window.screen.colorDepth;
var colors = Math.pow(2,depth);
document.write(depth + "bits which means" + colors +
"colors");
</script>
</head>
<body>
</body>
</html>
Here the depth will give an answer in bits and colors will be 2 ^depth. The
result will be as follows.
The document.getElementByid(id) which has been used in the last two chapters
in particular with objects.
The console.log used for debugging purposes. This has not been used in this
book but do not stop from using if appropriate.
Appendix I. Creating a simple drop down menu
No book on JavaScript can be complete without bringing up the subject of
menus. There are many ways menus can be designed. They can be designed
completely without JavaScript. To use JavaScript however the most common
way is to use three parts to the code.
The first part in the header is the cascading style sheet. This (css) is a separate
subject in itself. It can be either external in a text file or inline as in the
examples shown here.
The second part is the JavaScript which will do the functions of opening the
menu and letting users scroll and select.
The third part is the html script in the body of the web page. As mentioned
before a good knowledge of html and css is required to fully utilize JavaScript.
Let us take the following style sheet details.
<html>
<head>
<style>
#f1
{ margin: 0;
padding: 0;
z-index: 30}
#f1 li
{ margin: 0;
padding: 0;
list-style: none;
float: left;
font: bold 11px arial}
#f1 li a
{ display: block;
margin: 0 1px 0 0;
padding: 4px 10px;
width: 60px;
background: #5970B2;
color: #FFF;
text-align: center;
text-decoration: none}
#f1 li a:hover
{ background: #49A3FF}
#f1 div
{ position: absolute;
visibility: hidden;
margin: 0;
padding: 0;
background: #EAEBD8;
border: 1px solid #5970B2}
#f1 div a
{ position: relative;
display: block;
margin: 0;
padding: 5px 10px;
width: auto;
white-space: nowrap;
text-align: left;
text-decoration: none;
background: #cccccc;
color: #2875DE;
font: 11px arial}
The style sheet will give the colors, backgrounds and sizes of a menu and its
drop down elements. Only one part of the menu is being shown. One can repeat
the same process to develop a larger menu.
The menu shown here will show the word “Home” and when the mouse is
placed over it the drop down links will be Link one, Link two, Link three
respectively.
The next part of the code is that related to the body of the web page. The body
in this case includes a <div> statement similar to the ones in the chapter on
moving objects.
The code starts with identifying the element in the style or cascading sheet
code that will give the shape of the page. This is given by the id = f1 line. Thus
the style of the page will be set from the details provided in the style sheet.
Any style sheet can be used and the design of the style sheet will not affect the
JavaScript code above.
The code for the body of the web page is as follows.
<body>
<ul id="f1">
<li><a href="#"
onmouseover="openmenu('m1')"
onmouseout="menuclosetime()">Home</a>
<div id="m1"
onmouseover="menucanceltime()"
onmouseout="menuclosetime()">
<a href="#">Link one</a>
<a href="#">Link two</a>
<a href="#">Link three</a>
</div>
</li>
</ul>
<div style="clear:both"></div>
</body>
</html>
The id of the next menu if the user wants to create it will be m2 and so on.
Appendix II. References
I compiled this book for a web page development class at the undergraduate
level.
Computer code was referred from the following sources and modified as
needed for the chapters:
https://www.w3schools.com
https://docs.microsoft.com/en-us/scripting/javascript/writing-javascript-code
https://developer.mozilla.org