0% found this document useful (0 votes)
0 views

Chapter 4 JavaScript

Chapter Four covers the fundamentals of JavaScript, including its history, syntax, and capabilities for adding interactivity to web pages. It explains how to embed JavaScript in HTML, the differences between JavaScript and Java, and the use of variables, operators, and conditional statements. The chapter also discusses how to handle browsers that do not support JavaScript and the importance of variable scope.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Chapter 4 JavaScript

Chapter Four covers the fundamentals of JavaScript, including its history, syntax, and capabilities for adding interactivity to web pages. It explains how to embed JavaScript in HTML, the differences between JavaScript and Java, and the use of variables, operators, and conditional statements. The chapter also discusses how to handle browsers that do not support JavaScript and the importance of variable scope.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter Four: JavaScript

Topics:-  JavaScript operators  JavaScript objects


 What is and What Can  JavaScript functions  JavaScript HTML DOM
JavaScript Do?  JavaScript conditional objects
 How and Where do you statements and loops  Form Validation
place JavaScript code?  JavaScript events
Introduction to JavaScript
 JavaScript started life as LiveScript, but Netscape changed the name, possibly because of the excitement
being generated by Java.to JavaScript. JavaScript made its first appearance in Netscape 2.0 in 1995 with a
name LiveScript.
 JavaScript brings a dynamic functionality to your websites.
 It offers effects that are not otherwise possible, because it runs inside the browser and has direct access to
all the elements in a web document.
 JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as
Internet Explorer, Mozilla, Firefox, Netscape, Opera.
What is JavaScript?
 JavaScript is a scripting language designed primarily for adding interactivity to Web pages and creating
Web applications.
 JavaScript is the scripting language of the Web (a scripting language is a lightweight programming
language).
 JavaScript code is usually embedded directly into HTML pages.
 JavaScript is an interpreted language (means that scripts execute without preliminary compilation).
 Complementary to and integrated with Java and HTML.
 Open and cross-platform, everyone can use JavaScript without purchasing a license.
 JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and
much more.
What Can JavaScript Do?
 JavaScript gives HTML designers a programming tool.
 JavaScript can put dynamic text into an HTML page.
 JavaScript can improve the user interface of a website.
 JavaScript can react to user inputs and events.
 JavaScript can read and write HTML elements.
 JavaScript can be used to validate data.
 JavaScript can be used to create cookies.
JavaScript Syntax? This is where the JavaScript start
➢The HTML <script> tag is used to insert a JavaScript into an HTML page.
<body>
<script language="javascript" type="text/javascript">

document.write("<h1>Hello World!</h1>");
</script>

</body> This is where the JavaScript ends

Example Explained
 To insert a JavaScript into an HTML page, we use the <script> tag.

1 | P a g e Fundamental of Internet Programming (JavaScript)


 Inside the <script> tag we use the type attribute to define the scripting language.
 So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends.
 The document.write command is a standard JavaScript command for writing output to a page.
 The script tag takes the following important attributes:
 Language: The language attribute is used to designate that JavaScript is the scripting language being
used.
 Normally, its value will be “JavaScript”.
 To inform the browser that your code is JavaScript, you must add the attribute of this attribute to
the script tag.
 Type: This attribute specifies the scripting language of the script,
 It’s value should be set to "text/JavaScript".
 SRC : This attribute specifies the location of an external script
 Its value should be set to "JavaScript"
TYPE and LANGUAGE have a similar function, we use LANGUAGE to specify the language used in
the script.
➢N.B: If we had not entered the <script> tag, the browser would have treated the document.write("Hello
World!") command as pure text, and just write the entire line on the page.
How to Handle Simple Browsers
Problem
➢Browsers that do not support JavaScript, will display JavaScript as page content.
➢Solution
➢To prevent them from doing this, the HTML comment tag should be used to "hide" the JavaScript.
➢Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of javascript).
<script type="text/javascript">
<!--
document.write("Hello World!");
//--> </script>
➢The two forward slashes at the end of comment line (//) is the JavaScript comment symbol.
➢Three ways to insert JavaScript to HTML Web page:
1) JavaScript <body> Section
2) JavaScript in <head> Section
3) External JavaScript
Scripts in <head> Section
➢Scripts to be executed when they are called, or when an event is triggered, are placed in functions and put in
the head Section of your HTML document.
<html>
<head>
<script type="text/javascript"> function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Scripts in <body> Section
➢Scripts can be placed in the <body> Section of your HTML document.
<html>
<body >
<input type=”button” value=”Display” onclick=”message()”>
<script type="text/javascript"> function message()

2 | P a g e Fundamental of Internet Programming (JavaScript)


{
alert("This alert box was called with the onclick event");
}
document.write(“Scripts in the Body Section”);
</script>
</body></html>
Scripts in <body> and <head>
You can have scripts in both the body and the head section.
<html> <head>
<script type="text/javascript"> function message()
{
alert("This alert box was called with the onclick event from the Head Section");
}
</script>
</head>
<body >
<input type=”button” value=”Display” onclick=”message()”>
<script type="text/javascript">
document.write(“Scripts in the Body Section”);
</script>
</body>
</html>
Using an External JavaScript
 If you want to run the same JavaScript on several pages, without having to write the same script on every
page, you can write a JavaScript in an external file.
 Save the external JavaScript file with a .js file extension.
 Note: The external script cannot contain the <script> </script> tags!
 To use the external script, point to the .js file in the "src" attribute of the <script> tag.
<html><head>
<script type="text/javascript" src="abc.js"></script>
</head>
<body></body></html>
JavaScript and Java
 Are JavaScript and Java the Same? NO!,
 Java is a full-featured programming language developed by Sun Microsystems and a powerful and
much more complex programming language in the same category as C++.
 JavaScript is a trivial, interpreted programming language developed by Netscape for use within HTML
Web pages, therefore, JavaScript is not a Java.
 The table in below illustrates, the difference between JavaScript and Java.
JavaScript Java
It is interpreted by the client-side It is compiled on the server before executed on the
computer client machine
It’s a loose typing of data types It’s a strong typing of data types
In JavaScript, no need to declare data In Java data types must be declared
types
Its code is embedded in HTML Its code is not integrated in HTML
Its limited by the browser functionality Java applications are standalone

3 | P a g e Fundamental of Internet Programming (JavaScript)


It can access browser objects Java has no access to browser objects

JavaScript Statements
➢JavaScript is a sequence of statements to be executed by the browser.
➢JavaScript is Case Sensitive
Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you
write JavaScript statements, create or call variables, objects and functions.
➢JavaScript Statements
➢A JavaScript statement is a command to a browser. The purpose of the command is to tell the
browser what to do.
➢This JavaScript statement tells the browser to write "Hello
Dolly" to the web page: document.write("Hello Dolly");
➢JavaScript Code
➢JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is
executed by the browser
in the sequence they are written.
➢JavaScript Blocks
➢JavaScript statements can be grouped together in blocks.
➢Blocks start with a left curly bracket {, and ends with a right curly bracket}.
➢The purpose of a block is to make the sequence of statements execute together.
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>
➢JavaScript Comments
➢JavaScript comments can be used to make the code more readable.
➢JavaScript Single-line and Multi-Line Comments
➢Multi line comments start with /* and end with */.
➢Single line comments uses // .
➢<script type="text/javascript">
/*The code below will write one heading and two paragraphs*/
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>"); </script>
JavaScript Variables
➢Variables are "containers" for storing information.
➢JavaScript variables are used to hold values or expressions.
Rules for JavaScript variable names:
 Variable names are case sensitive, for example y and Y are two different variables.
 Variable names must begin with a letter or the underscore character
 You should not use any of the JavaScript reserved keyword as variable name.
Declaring (Creating) JavaScript Variables
You can declare JavaScript variables with the var statement:
Example:
➢var x; var pi = 3.1416;
➢var carname=”volvo”; Var str= “Hello world";
➢After the declaration shown above, the variable x is empty (no values yet). However, you can
also assign values to the variable when you declare it.

4 | P a g e Fundamental of Internet Programming (JavaScript)


JavaScript Reserved Words:
The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions,
methods, loop labels, or any object names.
abstract else instanceof switch static goto
boolean enum int synchronized super if
break export interface this import implements
byte extends long throw in debugger
case false native throws do default
catch final new transient double delete
char finally null true volatile short
class float package try while void
const for private typeof with public
continue function protected var return

Assigning Values to Undeclared JavaScript Variables


➢If you assign values to variables that have not yet been declared, the variables will
automatically be declared.
➢These statements:
➢X=5; carname="Volvo";
➢have the same effect as:
➢var x=5;
➢var carname="Volvo";
➢Redeclaring JavaScript Variables
➢If you redeclare a JavaScript variable, it will not lose its original value.
➢var x=5; var x;
JavaScript Variable Scope:
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only
two scopes.
Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript
code.
Local Variables: A local variable will be visible only within a function where it is defined. Function parameters
are always local to that function. Within the body of a function, a local variable takes precedence over a global
variable with the same name. If you declare a local variable or function parameter with the same name as a
global variable, you effectively hide the global variable. Following example explains it:
<script type="text/javascript"> <!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}//--></script>
This will produce
Local
JavaScript Operators
➢JavaScript Arithmetic
➢ you can do arithmetic operations with JavaScript variables

5 | P a g e Fundamental of Internet Programming (JavaScript)


➢y=x-5; z=y+5;
➢The assignment operator = is used to assign values to JavaScript variables.
➢The arithmetic operator + is used to add values together.
There are following arithmetic operators supported by JavaScript language: Assume variable y
holds 5
➢The + operator can also be used to add more string variables or text values together.
➢txt1="What a very"; txt2="nice day"; txt3=txt1 +'' ''+txt2;
➢If you add a number and a string, the result will be a string!

JavaScript Assignment Operators


➢Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators

JavaScript Comparison Operators


➢Comparison and Logical operators are used to test for true or false.
➢Comparison operators are used in logical statements to determine equality or difference
between variables or values.

➢Given that x=6 and y=3, the table below explains the logical operators

Logical Operators
 Logical operators are used to determine the logic between variables or values.

6 | P a g e Fundamental of Internet Programming (JavaScript)


 Given that x=6 and y=3, the table below explains the logical operators:

The Conditional Operator (? :)

There is an operator called conditional operator. This first evaluates an expression for a true or false value
and then execute one of the two given statements depending upon the result of the evaluation. The
conditional operator has this syntax:
Operato Descriptio
Example
r n

Conditional If Condition is true? Then value


?:
Expression X : Otherwise value Y

Conditional statements
➢Conditional statements are used to perform different actions based on different conditions.
➢Very often when you write code, you want to perform different actions for different decisions.
➢You can use conditional statements in your code to do this.
➢In JavaScript we have the following conditional statements:
If Statement
➢if statement - use this statement to execute some code only if a specified condition is true.
Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
➢<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date(); var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
If...else Statement
➢if...else statement - use this statement to execute some code if the condition is true and another code if the
condition is –
false. Syntax:
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
➢<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

7 | P a g e Fundamental of Internet Programming (JavaScript)


var d = new Date(); var time = d.getHours();
if (time < 10){
document.write("Good morning!");
} else{
document.write("Good afternoon!");} </script>
If...else if...else Statement
➢if...else if....else statement - Use the if....else if...else statement to select one of several blocks of code to be
executed.
Syntax:
if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
} else{
Statement(s) to be executed if no expression is true
}
<script type="text/javascript">
var d = new Date(); var time = d.getHours();
if (time<10){
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16){
document.write("<b>Good afternoon!</b>");
}else{
document.write("<b>Hello World!</b>");
}
</script>
Switch Statement
➢switch statement - use this statement to select one of many blocks of code to be executed.
Syntax:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
<script type="text/javascript">
var grade='A';
switch (grade){
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;

8 | P a g e Fundamental of Internet Programming (JavaScript)


case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}</script>
JavaScript Loops
➢Loops execute a block of code a specified number of times, or while a specified condition is true.
JavaScript Loops/for Loop/
➢for - loops through a block of code a specified number of times Syntax:
for(var=startvalue; for (initialization; test condition; iteration
var<=endvalue; statement){
var=var+increment) Statement(s) to be executed if test condition is
{ code to be executed } true}

Example:
<html><body>
<script type="text/javascript">
for(i=0;i<10;i++){
document.write("The number is: " + i);
document.write("<br />");
}</script>
</body></html>
JavaScript Loops/while Loop/
while - loops through a block of code while a specified condition is true Syntax:
while (var<=endvalue) while (expression){
{ Statement(s) to be executed if expression is true
code to be executed }
}
Example: <html><body>
<script type="text/javascript"> i=0; while (i<=5)
{
document.write("The number is " + i); document.write("<br />"); i++;
}
</script></body>/html>
The do...while Loop
➢This loop will execute the block of code once, and then it will repeat the loop as long as the specified condition
is true.
Syntax: do{
Statement(s) to be executed;
} while (expression);
Note the semicolon used at the end of the do...while loop.
Example: <script type="text/javascript">
var x = 1;
var sum = 0;
while ( x <= 10 ) { // loop until x is > 10
sum += x; // add x to the running sum
x++;}
document.write("The total sum is: " + sum); </script>
The break and continue statements
➢The break statement will terminate execution of the loop and continue executing the code that follows after
the loop (if any).

9 | P a g e Fundamental of Internet Programming (JavaScript)


➢The continue statement will terminate the current iteration and restart the loop with the next value.
Example: <script type="text/javascript">
var i=0;
for (i=0;i<=10;i++){
if (i==7){
break;
}else if(i==3){
continue;}
document.write("The number is " + i + "<br />"); }
</script>
JavaScript for...in Statement
➢The for...in statement loops through the elements of an array or through the properties of an object.
➢Syntax:
for (variable in object)
{code to be executed}
Example: <script type="text/javascript"> var x;
var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW";
for (x in mycars)//This loops through the arrays
{
document.write(mycars[x] + "<br />");

}</script>
JavaScript Functions
A function is a group of reusable code which can be called anywhere in your programme. This eliminates the
need of writing same code again and again. This will help programmers to write modular code. You can divide
your big programme in a number of small and manageable functions. Like any other advance programming
language, JavaScript also supports all the features necessary to write modular code using functions.
 A function will be executed by an event or by a call to the function.
 To keep the browser from executing a script when the page loads, you can put your script into a function.
 You may call a function from anywhere within a page (or even from other pages if the function is
embedded in an
 JavaScript lets you define functions using the function keyword
 Functions can return values using the return keyword.
Syntax:
function function name(var1,var2,...,varX)
{ some code
}
➢The parameters var1, var2, etc. are variables or values passed into the function.
➢The { and the } defines the start and end of the function.
Example:
A simple function that takes no parameters called sayHello is defined here:
<script type="text/javascript"><!--
function sayHello()
{alert("Hello there");
}
//-->

10 | P a g e Fundamental of Internet Programming (JavaScript)


</script>
Calling a Function:
To invoke a function somewhere later in the script, you would simple need to write the name of that function as
follows:
<script type="text/javascript"> <scripttype="text/javascript">
<!-- function area(length,width){
sayHello(); return length*width;
//--> }
</script> </script></head>
<body>
<scripttype="text/javascript">
document.write(area(10,15));
</script>
JavaScript return Statement
➢The return statement is used to specify the value that is returned from the function.
➢So, functions that are going to return a value must use the return statement.
<html><head> <script type="text/javascript"> function product(a,b)
{
return a*b;
}
</script></head>
<body>
<script type="text/javascript"> document.write(product(4,3));
</script></body></html>
JavaScript Dialog Boxes
➢JavaScript has three kind of popup boxes:
 These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of
input from the users. Here we will discuss each dialog box one by one
 Alert Dialog Box
 An alert dialog box is mostly used to give a warning message to the users.
 For example, if one input field requires to enter some text but the user does not provide any input, then as
a part of validation, you can use an alert box to give a warning message.
 Nonetheless, an alert box can still be used for friendlier messages.
 Alert box gives only one button "OK" to select and proceed.
 An alert box is often used if you want to make sure information comes through to the user.
➢Syntax: alert("sometext");
<html><head> </body></html>
<script type="text/javascript"> function
show_alert()
{
var r=alert("This is an alert box!");
}
</script>
</head><body>
<input type="button" onclick="show_alert()"
value="Show Alert box" />
➢Confirm box-A confirm box is often used if you want the user to verify or accept something.
➢When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
➢If the user clicks "OK", the window method confirm will return true. If the user clicks "Cancel", the box
returns false.

11 | P a g e Fundamental of Internet Programming (JavaScript)


JavaScript Popup Confirm Example:
<html><head> <input type="button" onclick="show_confirm()"
<script type="text/javascript"> function value="Show Confirm box" /></body></html>
show_confirm(){
var r=confirm("Press a button");
if (r==true) { alert("You pressed OK!");}
else{alert("You pressed Cancel!");}}
</script> </head> <body>

JavaScript Popup Prompt box


The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to
interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you
want to display in the text box (ii) A default string to display in the text box.
This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt()
will return entered value from the text box. If the user clicks on the Cancel button the window method prompt()
returns null.
➢Syntax: prompt("sometext","defaultvalue");
<head> <input type="button" onclick="show_ prompt
<script type="text/javascript"> function ();" value="Show Confirm box" />
show_prompt() </body></html>
{ var name=prompt("Please enter your
name","Harry
Potter");
//if (name!=null && name!="")
{
document.write("Hello " + name + "! How are
you
today?");}
}
</script> </head> <body>

JavaScript Events
What is Event?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
 By using JavaScript, we have the ability to create dynamic web pages.
 Events are actions that can be detected by JavaScript.
 Events are signals generated by the browser when various actions occur.
 Every element on a web page has certain events which can trigger a JavaScript.
 We define the events in the HTML tags.
 Events are normally used in combination with functions, and the function will not be executed before the
event occurs!
 JavaScript enables the designer of an HTML page to take advantage of events for automated navigation,
client-side processing, and more.
Example:-
 When the page loads, it is called an event.
 When the user clicks a button, that click too is an event.
 When an image has been loaded
 When the mouse clicks and moves over an element
 When an input field is changed

12 | P a g e Fundamental of Internet Programming (JavaScript)


 When an HTML form is submitted
 When a user strokes a key
 Events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) and every HTML element contains a set of events
which can trigger JavaScript Code. Please go through this small tutorial for a better understanding HTML Event
Reference.
 The events supported by JavaScript are listed in below:
 Click:-Occurs when the user clicks on a link, an image map area, or a form element.
 Change: -Occurs when the user changes the value of a form field.
 focus :-Occurs when the user gives input focus to a form element or a window.
 Load:- Occurs when a page or image has finished loading into the browser window.
 Unload-Occurs when the user exits a page.
 mouseOut:- Occurs when the user moves the mouse pointer from inside a link or image area’s
bounding box to its outside.
 mouseOver: Occurs when the user moves the pointer over a hypertext link or an image area.
 submit : Occurs when the user submits a form via the Submit button.
JavaScript Events Handlers
 Event handlers correspond to their associated events.
 They are scripts that execute automatically when events occur.
 Most deferred JavaScript functions are called by event handlers.
 Events are actions that do not have any direct influence.
 They only serve the event handlers.
 Each event handler is associated with an event.
 Event handlers are embedded in documents as attributes of HTML tags to which you
assign JavaScript code.
 You can use more than one event handler with the same HTML tag.
 The names of the event handlers are constructed of the word “on” and the name of the event.
 Here is the list of commonly supported JavaScript event handlers:
 Event handlers are not case sensitive.
 For example, you can use ONLOAD instead of onLoad.
JavaScript Event Handlers examples
onclick Event Type:
This is the most frequently used event type which occurs when a user clicks mouse left button. You can put your
validation, warning etc against this event type.
Example:
<html><head><script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}//-->
</script></head><body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body></html>
onsubmit event type:
This event occurs when you try to submit a form. So you can put your form validation against this event type.
The onSubmit event is used to validate all form fields before submitting it.
Example:
The checkForm() function will be called when the user clicks the submit button in the form.

13 | P a g e Fundamental of Internet Programming (JavaScript)


➢If the field values are not accepted, the submit should be cancelled.
➢The function checkForm() returns true the form will be submitted otherwise it will not submit the data.
➢If it returns true the form will be submitted, otherwise the submit will be cancelled.
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
onmouseover and onmouseout:
These two event types will help you to create nice effects with images or even with text as well. The
onmouseover event occurs when you bring your mouse over any element and the onmouseout occurs when you
take your mouse out from that element.
onLoad and onUnload- are triggered when the user enters or leaves the page.
 onload- A page or an image is finished loading
 The onLoad event is often used to check the visitor's browser type and browser version, and load the
proper version of the web page based on the information.
 onunload - The user exits the page
 Both are used to deal with cookie that should be set when a user enters or leaves a page.
onFocus, onBlur and onChange
 The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Example: <html><head>
<script type="text/javascript">
function upperCase() {
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script></head><body>
Enter your name:
<input type="text" id="fname" onblur="upperCase()">
</body></html>
Some other Events Handlers:-
 onabort - Loading of an image is interrupted
 onblur- An element loses focus
 onchange - The content of a field changes
 ondblclick - Mouse double-clicks an object
 onerror - An error occurs when loading a document or an image
 onfocus - An element gets focus
 onkeydown - A keyboard key is pressed
 onkeypress - A keyboard key is pressed or held down
 onkeyup- A keyboard key is released
 onload- A page or an image is finished loading
 onmousedown - A mouse button is pressed
 onmousemove - The mouse is moved
 onmouseout - The mouse is moved off an element
 onmouseover- The mouse is moved over an element
 onmouseup - A mouse button is released
 onreset - The reset button is clicked
 onresize - A window or frame is resized
 onselect - Text is selected
 onunload - The user exits the page
JavaScript special Characters
➢Insert Special Characters
➢The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.
➢JavaScript ignores extra spaces.

14 | P a g e Fundamental of Internet Programming (JavaScript)


➢You can add white space to your script to make it more readable.

JavaScript Objects Introduction


➢JavaScript as a programming language has strong object-oriented capabilities.
➢An OOP language allows you to define your own objects and make your own variable types.
➢An Object-Oriented (OOL) language enables you to model data using objects consisting of properties and
methods.
➢An object has properties and methods.
➢Properties are the values associated with an object.
Example:We are using the length property of the String object to return the number of characters in a string and
toUpperCase() method of the String object to display a text in uppercase letters.
<script type="text/javascript">// StringJavaScript object has length property and toUpperCase() method
var txt="Hello World!"
document.write(txt.length)
document.write(txt.toUpperCase())
</script>
 Methods are the actions that can be performed on objects.
 HTML DOM methods are actions you can perform on HTML Elements (like add or deleting an HTML
element).
 HTML DOM properties are values (of HTML Elements) that you can set or change.
JavaScript Objects
➢The String object is used to manipulate a stored piece of text.
➢The Date object is used to work with dates and times.
➢The Array object is used to store multiple values in a single variable.
➢The Boolean object is used to convert a non-Boolean value to a Boolean value (either true or false).
➢The Math object allows you to perform mathematical tasks.
JavaScript Object vs. Java Object
 Simlarities
 Both has properties and methods
 Differences
 JavaScript object can be dynamically typed while Java object is statically typed
 In JavaScript, properties and methods are dynamically added
JavaScript String Object
➢The String object is used to manipulate a stored piece of text.
➢The String object is a core JavaScript object that allows you to treat strings as objects.
➢String objects are created with new String().
➢Syntax: var txt = new String(string); or more simply:
➢var txt = string;
String Object Methods

15 | P a g e Fundamental of Internet Programming (JavaScript)


 The charAt() method returns the character found at a specified position within a string.
 concat()-Joins two or more strings, and returns a copy of the joined strings.
 toUpperCase()-Returns the calling string value converted to uppercase.
 toString()-Returns a string representing the specified object.
 replace(searchValue, replaceValue)- Replaces searchValue with replaceValue.
JavaScript Date Object
➢The Date object is used to work with dates and times.
The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( )
➢There are four ways of instantiating a date:
var d=new Date();
var d=new Date(milliseconds);
var d=new Date(dateString);
var d=new Date(year, month, day, hours, minutes, seconds, milliseconds);
Note: Paramters in the brackets are always optional
Here is the description of the parameters:
No Argument: With no arguments, the Date( ) constructor creates a Date object set to the current date and time.
milliseconds: When one numeric argument is passed, it is taken as the internal numeric representation of the
date in milliseconds, as returned by the getTime( ) method.
datestring:When one string argument is passed, it is a string representation of a date, in the format accepted by
the Date.parse( ) method.
Date Object Methods

JavaScript Array Object


➢The Array object is used to store multiple values in a single variable.
➢Create an Array
➢The following code creates an Array object called myCars:
1: var myCars=new Array(); // regular array myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW";
2: var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3: var myCars=["Saab","Volvo","BMW"]; // literal array
Access an Array document.write(myCars[0]);
Modify Values in an Array myCars[0]="Opel"; document.write(myCars[0]);

16 | P a g e Fundamental of Internet Programming (JavaScript)


Array Object Methods

JavaScript HTML DOM (Document Object Model)


What is the DOM?
 The DOM is a W3C (World Wide Web Consortium) standard.
 The DOM defines a standard for accessing documents:
 "The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content, structure,
and style of a document."
 When a web page is loaded, the browser creates a Document Object Model of the page.
 The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
What is the HTML DOM?
 The HTML DOM is a standard object model and programming interface for HTML. It
defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
 In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
HTML DOM Objects
 Anchor object  Form and Form Input object
 Document object  Frame, Frameset, and IFrame
 Event object objects

17 | P a g e Fundamental of Internet Programming (JavaScript)


 Image object  Screen object Window object
 Location object  Table, TableHeader, TableRow,
 Navigator object TableData objects
 Option and Select objects

Document Object
Example:
<html><body>
<script type="text/javascript">
document.write("Hello World!") // Write text to the output
document.write("<h1>Hello World!</h1>") // Write text with Formatting to the output
</script> </body></html>
Document Object: Use getElementsByName()
Example:
<html>
<head>
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("myInput")
alert(x.length + " elements!")
}</script></head><body>
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<br />
<input type="button" onclick="getElements()" value="How many elements named
'myInput'?">
</body></html>
Document Object: Return the innerHTML of the first anchor in a document
Example:
<html><body>
<a name="first">First anchor</a><br />
<a name="second">Second anchor</a><br />
<a name="third">Third anchor</a><br /><br />
InnerHTML of the first anchor in this document:
<script type="text/javascript">
document.write(document.anchors[0].innerHTML)
</script>
</body>
</html>

18 | P a g e Fundamental of Internet Programming (JavaScript)


JavaScript Form Validation
There's nothing more troublesome than receiving orders, guestbook entries, or other form submitted
data that are incomplete in some way. You can avoid these headaches once and for all with
JavaScript's amazing way to combat bad form data with a technique called "form validation".
The idea behind JavaScript form validation is to provide a method to check the user entered
information before they can even submit it.
➢JavaScript can be used to validate data in HTML forms before sending the content to a server.
JavaScript also lets you display helpful alerts to inform the user what information they have entered
incorrectly and how they can fix it. In this, We will check for the following:
 If a text input is empty or not
 If a text input is all numbers
 If a text input is all letters
 If a text input is all alphanumeric characters (numbers & letters)
 If a text input has the correct number of characters in it (useful when restricting the
length of a username and/or password)
 If an email address is invalid
 How to check all above when the user has completed filling out the form

References
HTML Tutorial: http://www.w3schools.com/html
CSS Tutorial: http://www.w3schools.com/css
JavaScript Tutorial: http://www.w3schools.com/js

19 | P a g e Fundamental of Internet Programming (JavaScript)

You might also like