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

Unit 4 Notes

Uploaded by

sribalajibolloju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Unit 4 Notes

Uploaded by

sribalajibolloju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT-IV INTRODUCTION TO JAVASCRIPT

JavaScript and Forms, Variables, Functions, Operators, Conditional Statements and Loops, Arrays, DOM Methods,
Strings, JavaScript Closures (Local and Global Variable) , JSON. Events Handling (Mouse Events, Keyboard Events).

JavaScript is the acronym for “Scottish Centre for Research in Intellectual Property and Technologies” Script:
Any program run by web server in response to user’s request is termed as script. Scripting languages are the basis
of the CGI-BIN programming that is currently used to add a limited form of interactivity to Web pages. Web pages
a basically of two types as Server side script and Client side script language.
Most popular & default client side script is JS(Java script).

What is JavaScript?
• JavaScript is a lightweight, interpreted programming language with object-oriented capabilities.
• Designed for creating network-centric applications
• Complementary to and integrated with Java
• Complementary to and integrated with HTML
• Open and cross-platform
• JavaScript is usually embedded directly into HTML pages
• JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

BENEFITS OF JAVASCRIPT
JavaScript has a number of big benefits to anyone who wants to make their Web site dynamic:
1. It is widely supported in Web browsers
2. it gives easy access to the document objects and can manipulate most of them
3. JavaScript can give interesting animations without the long download times associated with many
multimedia data types
4. JavaScript is relatively secure — JavaScript can neither read from your local hard drive nor write to it, and
one can’t get a virus infection directly from JavaScript.
5. JavaScript allow many page effects Some page effects that JavaScript allows are: User's time
on page Popups and tooltips
Collapsing text Page timeout
Color changes and fades Embedded audio
Print page/element Scrolling banners
Flying text Automated popups
Image transitions

6. JavaScript will add user interactivity The special effects that are added to the web page will make it more
interactive. The user/visitor of your website will want to keep exploring within the web site.
7. JavaScript will allow client-side user form validation If JavaScript is available, an initial validation of the
website's client can be done to check for simple errors such as missing information or non-numeric
characters mistakenly placed in a non-numeric field. As a result, the user of the website gets faster
feedback than having to wait for a response from the server.

ADVANTAGES OF JAVA SCRIPTING LANGUAGE

• An interpreted language – JavaScript is an interpreted language, which requires no compilation steps. This
provides an easy development process. The syntax is completely interpreted by the browser just as it
interprets HTML tags.
• Embedded within html – JavaScript does not require any special or separate editor for programs to be
written ,edited or compiled. It can be written in any text editor like notepad, along with appropriate HTML tags
, and saved as filename.html.
• JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but
JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code
into their HTML pages
• JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a
page has finished loading or when a user clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is
submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect
the visitor's browser, and - depending on the browser - load another page specifically designed for that
browser
• JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on
the visitor's computer

Are Java and JavaScript the same? NO!


Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the
same category as C and C++.

How to Insert JavaScript into a HTML page:


You can insert JavaScript into an HTML page by using <script> tag.
JavaScript is placed between tags starting with <script language =”javascript”> and ending with
</script>.
The script tag attributes:
i. Language: scripting language name
ii. type: internet content type for a scripting language iii src:
URL for an externally linked script

General syntax of JavaScript is as follows:


<script language="javascript">
... //JavaScript code snippet written here
</script>

Different places where JavaScript can be placed in HTML:

JavaScript can be placed in various locations in HTML such as


• JavaScript in HEAD section
• JavaScript in BODY section
• JavaScript in both HEAD and BODY section
• JavaScript in External File

JavaScript is traditionally embedded into a standard html program. Javascript is embedded between the
<script>..</script> tags. These tags can are embedded within the <head>…</head> or <body>…</body> tags
of the html program.
The placing of JavaScript in the above location differs in the timing of their execution. JavaScript placed in the
HEAD section of HTML will be executed when called ,whereas, JavaScript placed in the BODY section of HTML will
be executed only when the page is loaded.

The general structure for placing a JavaScript in the HEAD section is:
<html> <head>
<script language="javascript">
..... //JavaScript written in HEAD Section
</script>
</head>
<body> </body></html>

The general structure for placing a JavaScript in the BODY section is

<html>
<head> </head>
<body>
<script language="javascript">
.....
..... //JavaScript written in BODY Section
</script>
</body> </html>

Basic Rules
JavaScript programs contain variables, objects, and functions. The key points that you need to apply in all scripts
are listed below.

1. JavaScript statements end with semi-colons. (Each line of code is terminated by a semicolon)
2. JavaScript is case sensitive.
3. JavaScript has two forms of comments:
o Single-line comments begin with a double slash (//).
Ex.: // comment type-1
o Multi-line comments begin with "/*" and end with "*/". Ex:
/* more than one line */
4. Blocks of code must be surrounded by a pair of curly brackets. A block of code is a set of instructions that
are to be executed together as a unit
5. Variables are declared using the keyword var.
6. Functions have parameters which are passed inside parentheses.
7. Scripts require neither a main function nor an exit condition

How to display content on Browser using Java script ?


The JavaScript command used for writing output to a page is document.write. The document.write command takes
the argument as the text required for producing output.
The example below shows how to place JavaScript command inside an HTML page :
Example:
The document. write command is a standard JavaScript command for writing output to a page. By entering the
document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript
command and execute the code line. In this case the browser will write javascript is not java to the page.
Example:
<script language="javascript">
document.write("JavaScript is not Java"); // javascript statement
</script>
JavaScript Variables:
JavaScript has variables. Variables can be thought of as named containers to place data and then refer to the data
simply by naming the container. Variables are used to hold data in memory.
Variables are declared with the var keyword as follows:
<script
type="text/javascript
"> var money;
var name;
</script>
Example:-
• Single variable declaration
o var age;
• Multiple variables can be declared in a single step.
o var age, height, weight, gender;
• After a variable is declared, it can be assigned a value.
age = 34;
• Variable declaration and assignment can be done in a single step.
var age = 34;
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.

JavaScript Variable Names:


There are strict rules governing how you name your variables in JavaScript:
• JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the
underscore character. For example, 123test is an invalid variable name but
• _123test is a valid one.
• A underscore ( _ ) can be used as a separator in case of multiple words.
• cannot use spaces in names;
• JavaScript variable names are case sensitive. For example, Name and name are two different variables.
• Cannot use a reserved word as a variable name. Reserved words are those words which are part of the
JavaScript language.
visitor_name = visitor_name + 45.32
but might accidentally write: vn = vn + 45.32.
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.

DATA TYPES
JavaScript uses four data types-numbers, strings,
Boolean and a null
Numbers
Using the numbers, it is possible to express both
integers and floating point values. These are basic
numbers. They can be integers such as 2, 22, and 2,222,000 or floating point values like 23.42, —56.01, and 2E
45.
Strings
These are collections of characters that are not numbers. Single-quoted or double-quoted (both the same).
The value of a string can even contain spaces and may be totally made from digits. All of the following are
strings:“Chris”, “Chris Bates”, and “2345.432”.

Boolean
Variables hold the values true and false.

NULL
The null value is a special value in JavaScript. The null value represents just that-nothing
The null value is indicated in JavaScript by the term null. It does not mean nil or zero and should not be used in
that way- ever.

DIALOG BOXES (POPUP BOXES) (WINDOW OBJECT)


One can use JavaScript to create popup windows. Popup windows are different to simply opening a new browser
window. Basically three types of popup boxes are created using JavaScript code depending on the needs of user,
Three kinds of popup boxes created using JavaScript are:
• Alert box
• Confirm box
• Prompt box
ALERT BOX:
The JavaScript alert box is useful for alerting the users to something important. When a JavaScript alert
box is triggered, a small box will pop up and display the text that is specified in the JavaScript code. This type of
popup box is a dialog box used when a programmer wants to make
sure that the information is passed to the user. The alert box pops up with an OK button which the user has to
press to continue.
General syntax of alert box is : alert(“textmessage”) For
example: alert(“welcome to javascript”)
The above statement will display a dialog box with message welcome to javascript and a OK button. The dialog box
remains in view until the user presses the OK button. When no text message is placed alert()

CONFIRM BOX:

The JavaScript confirm box gives a chance to confirm an action before JavaScript runs it. The 'confirm' box
is created using JavaScript's built-in confirm() function. When the JavaScript confirm() function is triggered, a
small box will pop up and display an "OK" button and a "Cancel" button (along with text that specified in JavaScript
code). The confirm box is a box that pops up with both an OK and a Cancel button. The confirm box is used to
verify acceptance from the user. If the user accepts, then the user presses the OK button and the confirm box
returns with a true value. If the user rejects with the Cancel button, then the confirm box returns false value.

General syntax for a confirm box is : confirm (“textmessage”)


<html><body>
<script language=”javascript">
var x=confirm("if u do hardwork")) if (x)
alert (" Will get good marks")
else
alert ("will get less marks")
</script></body>
</html>

PROMPT BOX:
The JavaScript prompt box prompts the user to input text. The 'prompt' box is created using JavaScript's built-in
prompt() function. When the JavaScript prompt() function is triggered, a small box will pop up and display a
message to the user (written as the argument of the function), a text field (for the user's input), an "OK" button,
and a "Cancel" button are displayed.
This box is used when a user have to input values for the script, If the user presses OK then the prompt
box returns with the value entered by user but if the user presses the Cancel button then the prompt box returns
with a null value.
By default values are accepted as string data type, to convert these string values to a numeric value
parseInt or parseFloat conversion functions are implemented.

General syntax of prompt box is as follows: prompt(“textmessage”,”value_default”)


<html>
<body>
<script type="text/javascript">
name = prompt("Input the user name","srinivas")
</script>
</body>
</html>

JAVASCRIPT OPERATORS
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is
called operator. JavaScript language supports following type of operators
a) Arithmetic operators b) Comparison operators
c) Logical operators d) Assignment operators
e) Conditional operator e) The + operator used on strings

Arithmetic operators:
These operators take numerical values (either literals or variables) as their operands and return a single
value. The standard arithmetic operators are listed below
Assume variable a holds 10 and variable b holds 20 then:

operator Description Example


+ Adds two operands a + b will give 30
- Subtracts second operand from the first a - b will give -10
* Multiply both operands a * b will give 200
/ Divide the first number by the number b / a will give 2
% Divides the left by the right operand and calculates the remainder b % a will give 0
++ Increment operator, increases integer value by one a++ will give 11
-- Decrement operator, decreases integer value by one a-- will give 9
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

Comparison operators:
A comparison operator compares its operands and returns a logical value based on whether the
comparison is true or not. The comparison operators are listed below Assume variable a holds 10 and variable b
holds 20 then:
operator Description Example
== Returns true if the two operands are equal. (a == b) is not true.
!= Returns true if the two operands are not equal. (a != b) is true.
> Greater than returns true if the left operand is greater than the right. (a > b) is not true.

>= Returns true if the left operand is greater than or equal to the right one. (a >= b) is not true.

< Returns true if the left operand is less than the right. (a < b) is true.
<= Returns true if the left operand is less than or equal to the right one.. (a <= b) is true.
Logical operators:
These operators are typically used with Boolean (logical) values. They return a Boolean value. The Boolean
operators are listed below, Assume variable a holds 10 and variable b holds 20 then:
operator Description Example
&& Called Logical AND operator. If both the operands are non zero then (a && b) is true.
condition becomes true.

|| Called Logical OR Operator. If any of the two operands are non zero then (a || b) is true.
condition becomes true.

! Called Logical NOT Operator. Logical NOT returns false if the operand !(a && b) is false.
evaluates to true. Otherwise it returns true.

Assignment operators:
The assignment operators (=) to assign a value to a variable or constant or expression assigned for given
variable. The assignment operators are listed below
operator Description Example
= Assigns the value of the right operand to the left operand c = a + b will assign value of a + b into
c

+= Adds together the operands and assigns the result to the c += a is equivalent to c=c+a
left operand

-= Subtracts the right from left operand and assigns the result c -= a is equivalent to c=c-a
to the left operand

*= Multiplies the operands and assigns the result to the left c *= a is equivalent to c = c * a
operand

/= Divides the left by the right operand and assigns the result c /= a is equivalent to c=c/a
to the left operand

%= Divides the left by the right operand and assigns the c %= a is equivalent to c = c % a
remainder to the left operand

Conditional Operator (? :) :
JavaScript provides conditional operator (? :) which is used for comparing two expressions, also contains a
conditional operator that assigns a value to a variable based on some condition.
Syntax : variable=(condition)?value1:value2; Example:
result=(marks>=35) ? "Passed" : "failed";
Displays result depends on marks, if greater than are equal to 35 displays as passed otherwise displays failed
message.

The + Operator Used on Strings: The + operator can also be used to add string variables or text values
together. To add two or more string variables together, use the + operator.

txt1="What a very "; txt2="nice day"; txt3=txt1+txt2;


After the execution of the statements above, the variable txt3 contains "What a verynice day".

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

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. In JavaScript we have
the following conditional statements:

if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and another code if
the condition is false
if...else if .... else statement - use this statement to select one of many blocks of code to be
executed
switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified
condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase


letters (IF) will generate a JavaScript error!
Example
<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>
Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified
condition is true.

If ..... else Statement


Use the if....else statement to execute some code if a condition is true and another code if the condition is not
true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
<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.

var d = new Date();


var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!"); } </script>

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 (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}

Example
<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 day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement


Use the switch statement to select one of many blocks of code to be executed.
Syntax:
switch(n)
{
case 1:
execute code block 1
break;

case 2:
execute code block 2
break;
default
:
code to be executed if n is different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value
of the expression is then compared with the values for each case in the structure. If there is a match, the block of
code associated with that case is executed. Use break to prevent the code from running into the next case
automatically.

Example:<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
Document.writeln(“d.getDay()”+”<br>”);

switch (theDay)
{
case 5:
document.write("Finally
Friday"); break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
JAVASCRIPT LOOPS
Loops execute a block of code a specified number of times, or while a specified condition is
true. In JavaScript, there are two different kind of loops:
for - loops through a block of code a specified number of times
while - loops through a block of code while a specified condition is true

The for Loop


The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue; var<=endvalue; var=var+increment)
{
code to be executed
}
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as
i is less than, or equal to 5. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing
statement.
<html>
<body>
<script
type="jav
ascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The
number is " + i);
document.write("<br>"
);
}
</script>
</body>
</html>

JavaScript While Loop


Loops execute a block of code a specified number of times, or while a specified condition is true.
The while Loop
The while loop loops through a block of code while a specified condition is true.
Syntax
while (var<=endvalue)
{
code to be executed
}
Note: The <= could be any comparing statement.
Example: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<script
type="text/ja
vascript">
var i=0;
while (i<=5)
{
document.write("The
number is " + i);
document.write("<br
/>");
i++;
}
</script>
</body>
</html>
The do...while Loop
The do...while loop is a variant of the 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
{
code to be executed
}
while (var<=endvalue);

Example
The example below uses a do...while loop. The do...while loop will always be executed at least
once, even if the condition is false, because the statements are executed before the condition is
tested:
<html>
<body>
<script
type="text/ja
vascript">
var i=0;
do
{
document.write("The
number is " + i);
document.write("<br
/>");
i++;
}
while (i<=5);
</script></body></html>

ARRAYS
An array is an ordered set of data elements which can be accessed through a single variable name.

Basic Array Operations:


The basic operations that are performed on arrays are: creation, addition of elements, accessing
individual elements, removing elements

Creating Arrays JavaScript arrays can be constructed in no fewer than three different ways.

The first method is simply to declare a variable and pass it some elements in array format:
var days = [“Monday”, ‘Tuesday”, “Wednesday”, “Thursday”];
That creates an array of four elements, each holding a text string. Notice that the array of elements is
surrounded by square brackets. In most programming languages square brackets denote arrays and
array operations.

The second approach is to create an array object using the keyword new and a set of elements to
store: var days = new Array(”Monday”, “Tuesday”, “Wednesday”, “Thursday”);
Using this construct, the contents of the array are surrounded by parentheses because they are
parameters to the constructor of the Array object.

Finally an empty array object which has space for a number of elements can be created: var days =
new Array(4)
JavaScript arrays can hold mixed data types as the following examplesshow: var data = [“Monday”,
“Tuesday”, 34, 76.34,“Wednesday”];
var data = new Array(”Monday”, 34, 76.34,“Wednesday”);
Adding Elements to an Array Array elements are accessed by their index. The index denotes the
position of the element in the array and, as in for loops, these start from 0. Adding an element uses
the square bracket syntax we saw a moment ago:
var days[3] = “Monday”;

What happens if you want, or need, to add an item to an array which is already full? Many languages
struggle with this problem but JavaScript has a really good solution: the interpreter simply extends
the array and inserts the new item:
1. var data = [“Monday”, “Tuesday”, 34, 76.34,“Wednesday”];
2. data[5] = “Thursday”; 3. data[23] =48;

The code creates an array of four elements in line one. A new element is added at position 5 in line
two. At line three an element is added to position 23. To do this the array is first expanded so that it is
long enough and then the new element is added.

Object-based Array Functions:


In JavaScript, an "object-based array" typically refers to an array of objects. Each element in the
array is an object that can contain multiple key-value pairs or properties.
The declared array variable act like an object. The name of the array need to be opeated followed by
a dot (. Operator), then the name of the function. Finally in parentheses list of parameters are given
separated by coma.

Example to concatenate two array values


arrayname. function (parameter l, parameter2);concat (array2 [, array3 [, array N]])

A list of arrays is concatenated onto the end of the array and a new array returned. The original
arrays are all unaltered by this process. Here’s some code which concatenates three arrays:
<html>
<head>
<title>Arrays</title>
</head>

<body>
<script language="javascript">document.writeln("<h1>Concatenating Arrays</h1>");
var a = ["Monday", "Tuesday", 34, 76.34, "Wednesday"]; var b = ["one", "two", "three",
76.91];
var c = new Array("an", "object", "array"); var result = a.concat(b, c);
// Show the resultingarray document. write ("<p>"); var len =result.length;
for(var i = 0; i<len; i++) document.write(result[i] + ", ");document.writeln("</p>")
</script>
</body>
</html>

Some popular Array Methods:


join(string):it’s useful to have all of the elements in array joined together as a string. turns all
elements into strings and joins them together into a single string. With no arguments, a comma
separates the elements.

document.writeln("with joint operator<br>"+a.join())


document.writeln("with joint operator<br>"+a.join('#'))

push(elementl [, element2 [, elementN]]):Adds a list of items onto the end of the array. The items
are separated using commas in the parameter list.
var a=[12,14,56,78,67]
document.writeln(“given array”+a)
a.push(56)
document.writeln(“after addition”+a)

Pop():This function removes the last element from the array and in doing so reduces the number of
elements in the array byone.
var a=[12,14,56,78,67]
document.writeln(“given array”+a)
a.pop()
document.writeln(“after deleting”+a)

reverse (): As the name suggests, this function swaps all of the elements in the array so that which
was first is last, and vice versa.
a.reverse();

shift():Removes the first element of the array and in so doing shortens its length by one.
a.shift()

unshift (element1 [, e].ement2 [,elementN]]):Inserts a list of elements onto the front of the array.
The list of new elements can have just one item.
a.unshift(10)

slice(start[, finish]):need to extract a range of elements from an array. The slice () function does
exactly this. Two parameters are possible: the first element which you want to remove is specified in
the first parameter, the last element you want is specified in the second one. If you only give a single
parameter, all elements from the specified one to the end of the array are selected. Once the
elements have been sliced they are returned as a new array. The original array is unaltered by this
function.
d=a.slice(1,5)

sort(): uses string comparison to determine the sorting order (i.e., via ASCII values).
o sort takes an optional argument, the compare function returns below values.
<0 if first argument is smaller than the second
0 if arguments are equal
>0 if first argument is larger than the second

unshift (element1 [, e].ement2 [,element N]]):Inserts a list of elements onto the front of the array.
The list of new elements can have just one item.

Example : to demonstrate array methods.

<html>
<head>
<title>Array Operations</title></head>
<body>
<script language= "javascript"> document. writeln("<h1>Array Functions</h1>");
var first = ["Monday", "Tuesday", 34, 76.34, "Wednesday"]; document.write("<p>");
document.write(first.join(", ")); document.write
("<br>");first.pop();document.write(first.join(", ")); document.write("<br>");
first.push("one", "two", "three", 76.9);
document.write(first.join(",
"));document.write("<br>")first.reverse();document.write(first.join(",
"));document.write("<br>"); first.shift();
first.shift();document.write(first.join(", "));
document.writeln("</p>");document.close();
</script>
</body>
</html>

Example for unshift and push


DOM:
The DOM (Document Object Model) in JavaScript is an interface that represents the structure of a
document, such as an HTML or XML document. It provides a way for scripts to access and manipulate
the content and structure of a web page.

Using DOM JS can implement the following to an HTML page

• JavaScript can change all the HTML elements in the page


• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

Example figure 2

Example figure 3
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."

The HTML DOM is a standard object model and programming interface for HTML. It defines:

• The HTML elements as objects


• The properties (values) of all HTML elements
• The methods (Actions) 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.

• The HTML DOM can be accessed with JavaScript (and with other programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML element).
• A method is an action you can do (like add or deleting an HTML element).

HTML methods
Inner HTML
Inner Text
Outer HTML
Outer Text

Example to change the text in runtime

<!DOCTYPE html>
<html>
<body>

<h2>My First Page</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

the getElementById() method returns an element with a specified value. The getElementById()
method returns null if the element does not exist. The getElementById() method is one of the most
common methods in the HTML DOM.

HTML DOM Objects:- Objects of Document object module is nothing but the elements(tags) in HTML.
Almost all the element can be implement in event handling methods to inherit the properties which is
assigned dynamically. These objects can be used in any of the ways mentioned in the above chapter.
(using scripting or implementing as the attribute). One of the most important object of DOM is
Document which is used in multiple ways in this section. The details about the Document object and
the examples to implement it are given below.

Document Object Each HTML document loaded into a browser window becomes a Document object.
The Document object provides access to all HTML elements in a page, within a script.
Tip: The Document object is also part of the Window object, and can be accessed through the
window.document property.

Document Object Methods

Method Description
close() Closes the output stream previously opened with document.open()
getElementsByName() Accesses all elements with a specified name
open() Opens an output stream to collect the output from
document.write() or document.writeln()
write() Writes HTML expressions or Script language code to a document
writeln() Same as write(), but adds a newline character after each
statement

DOM Example 2: to change the background color


<HTML>
<HEAD>
<script>

function ch()
{
document.bgColor=document.f1.t1.value
}
</script>

</HEAD>

<BODY BGCOLOR="NAVYblue">
<form name=f1>
<input type=button style="background-color:red" value=red
onclick="document.bgColor='red'">
<input type=button value=green onclick="document.bgColor='green'">
<input type=button value=blue onclick="document.bgColor='blue'">
<input type=text name=t1>
<input type=button value=change onclick="ch()">

</html>

JAVA SCRIPT STRINGS


In JavaScript, strings are sequences of characters, represented using text within single, double, or
backticks (template literals). Strings are used to store and manipulate textual data in a JavaScript
program.
Creating Strings: Strings can be created using single quotes ('...'), double quotes ("..."), or backticks
(`...`).
Var st=”bhavans”

String Length: The length property of a string returns the number of characters in the string.
let text = "Hello World!";
let length = text.length;

Accessing Characters: Characters in a string can be accessed using square brackets ([]) and the
character's index (zero-based index).
const string = 'Hello';
const letter = string[1];

String Methods: JavaScript provides various methods to manipulate and work with strings, such as
toUpperCase, toLowerCase, charAt, indexOf, substring, replace, split

charAt: str.charAt(index): Returns the character at the specified index.


charCodeAt: str.charCodeAt(index): Returns the Unicode value of the character at the specified
index.
concat: str.concat(str1, str2, ..., strN): Concatenates two or more strings and returns a new string.
substring: str.substring(startIndex[, endIndex]): Returns a substring between the specified indices.
slice: str.slice(startIndex[, endIndex]): Returns a section of a string.
toUpperCase: str.toUpperCase(): Converts the string to uppercase.
toLowerCase: str.toLowerCase(): Converts the string to lowercase.
trim: str.trim(): Removes whitespace from both ends of a string.
replace: str.replace(searchValue, replaceValue): Replaces a substring with another substring.
split: str.split(separator[, limit]): Splits the string into an array of substrings based on a specified
separator.
search: str.search(regexp): Searches a string for a specified value and returns the position of the
match.
These methods allow you to manipulate and work with strings in various ways, making it easier to
handle and process textual data in your JavaScript programs.

Example for string handling functions


<html>
<head>
<title>JavaScript String Methods</title>
</head>
<body>
<script type = "text/javascript">
var str = new String( "This is string" );
document.writeln(“The Character In 0 Location Is :" + str.charAt(0));
document.write(“ASCI value of the character at 0 is :" + str.charCodeAt(0));
document.write("str.length is:" + str.length);
document.write( “sliced text=“+str.slice(3, -2);
document.write(“substring from 0 to 10 index: " + str.substring(0, 10));
(str.substring(5))
document.write(str.toLowerCase( ));
document.write(str.toUpperCase( ));
</script>
</body>
</html>
EVENTS IN DHTML:

Event handler is a website optimization technique that is generated whenever an event occurs. It is
basically a function or method which contains program statements that are executed in response to an
event. It is an asynchronous callback routine that processes actions such as keystrokes and mouse
movements.

Some of the GUI events are key presses, mouse movement, action selection and timers expiring. Web
site optimization by using event handlers on a lower level can also be possible. Events represent
availability of new data for reading a file or network stream.

Reasons to execute Event handlers for web site optimization are


• They are executed when a particular host or service is in a soft problem state or hard problem
state or recover from a soft or hard problem state.
• Events are handled in different ways in different languages. So web site optimization
techniques are decided upon the type of language used.
Web site optimization is very essential part of enhancing website

Two Ways of assigning event handlers


The 2 common and conventional ways of setting up an event handler- via HTML, or scripting. In both
cases, a function or code is attached at the end, which is executed when the handler detects the
specified event.

1) Via HTML, using attributes


It can be defined directly inside the relevant HTML tag, by embedding it as a attribute.
A piece of Script is also included to tell the browser to perform something when the event occurs.
For example to change the background color of the window.
Demo:
<body onclick=”document.bgColor=’red’”>
The event handler (onClick) is directly added inside the desired element (body), along with the DOM
method and property with user defined value.

2) Via scripting
This can be implemented to elements using scripting, and inside the script which allows the event
handlers to be dynamically set up, without having to mess around with the HTML codes on the page.
When setting up event handlers for an element directly inside the script,the code to execute for the
events must be defined inside a function.

Consider the example which does the same thing as above, but with the event handler defined using
scripting:
<html>
<head>
<script language=”JavaScript”>
function change()
{
document.bgColor=’red’”
}
</script>

<body>
<input type=button value=”change bgcolor” onclick=change>
</body>
</html>

TYPES OF EVENTS AND PROPERTIES:

An event is a notification that occurs in response to an action, such as a change in state, or as a result
of the user clicking the mouse or pressing a key while viewing the document. An event handler is
code, typically a function or routine written in a scripting language, that receives control when the
corresponding event occurs.

There are different types of event available with DHTMl some of them are listed below.

Types of Events Handlers


1. Keyboard Events
2. Mouse Events
3. Widow Events

Keyboard Events:-Keyboard events occur when the user presses or releases a keyboard key. The
onkeydown and onkeyup events fire when a key changes state as it pressed or released, respectively.
These events fire for all keys on the keyboard, including shift state keys such as SHIFT, CTRL, and
ALT.

Mouse Events:Mouse events occur when the user takes any action with the pointing device. When a
mouse event occurs, the button property of the event object identifies which mouse button, if any, is
pressed. The x and y properties specify the location of the mouse pointer at the time of the event. For
the onmouseover and onmouseout events, the toElement and fromElement properties specify the
elements the mouse is moving to and from.

Mouse Click events: Mouse click events are interspersed with onmousedown and onmouseup events.
Some of them are onmousedown,onmouseup,onclick,ondblclick.

Window Events :-Events which are occurred on the action taken on user window. The onload event
fires after the document is loaded and all the elements on the page are completely downloaded. The
onunload event fires immediately prior to the document being unloaded as when navigating to another
document.Specifying code for the onload and onunload events can be done on the BODY tag. these
events actually occur on the window object.
List of Events

HTML DOM events allow Script language to register different event handlers on elements in an HTML
document. Events are normally used in combination with functions, and the function will not be
executed before the event occurs (such as when a user clicks a button).

Mouse Events
Event Attribute Description
click onclick The event occurs when the user clicks on an element
dblclick ondblclick The event occurs when the user double-clicks on an
element
mousedown onmousedown The event occurs when a user presses a mouse button over
an element
mousemove onmousemove The event occurs when a user moves the mouse pointer
over an element
mouseover onmouseover The event occurs when a user mouse over an element
mouseout onmouseout The event occurs when a user moves the mouse pointer out
of an element
mouseup onmouseup The event occurs when a user releases a mouse button
over an element

Keyboard Events
Event Attribute Description
keydown onkeydown The event occurs when the user is pressing a key or
holding down a key
keypress onkeypress The event occurs when the user is pressing a key or
holding down a key
keyup onkeyup The event occurs when a keyboard key is released

Event Handlers Will be called when it required:


OnAbort The loading of an image is aborted as a result of user action
OnBlur A document, windows, or form element loses current input focus.
OnChange A text field, text area, or selection is modified and the current input focus
OnClick A link, client side image map or a document is clicked.
OnDblClick A link, client side image map or a document is double clicked.
OnDragDrop A dragged object is dropped in a window of frame
OnFocus A document, windows, or form element receives current input focus.
OnKeyUp The user releases a Key
OnLoad An image, document or frame set is loaded
OnMouseDown The user presses a mouse button
OnMouseMove The user moves the mouse
OnMouseOut The mouse is moved out of link or text or image map
OnMouseOver The mouse is over a link or text or client image map
OnMouseUp The user releases mouse button
OnReset The user resets a form by clicking on the form’s reset button
OnResize The user resizes a window or frame
OnSelect Text is selected in a text field or a text area
OnSubmit The user presses a form’s submit button
OnUnload The user exits a document or frame set

Changing Background Properties dynamically using mouse events


Changing the styles and properties of the text & Background dynamically can be implement with
event handling methods some of the examples given below explain the processes of dynamic changes
in DHTML.
Using Onmouseover, out, click in a single program.

<html>
<head>
<title>Event handling Examples</title>
</head>
<body onmousedown="document.bgColor='red'";
onmouseup="document.bgColor='blue'";
onclick="document.bgColor='green'">
<center>

<h1>See the page in red when mouse down<br><br>


And in blue when up<br><br>
In green when clicked is't great!!!!!!!!!!!!!!!<br><br>
</center></body>
</html>

• In the above examples the mouse event are used to change the background color of the current
web page.
• Document is indicated to inherit the changes to the current document.
• Observe (bgColor is used) as the property the second world 1st letter should be given in Capital.
• The values are enclosed within single ‘ ‘ and the statement is enclosed in “”
• Multiple values are specified by ;

Changing Font Properties dynamically:- All The font properties which are used in style sheet can
be implemented with event handlers and DOM methods which help the user to change the properties
dynamically. A Style object is used to set the properties for the selected text and This keyword
represent the current selected text and follows with the methods (Fontsize) is the method to be
implemented.
Programme to change the font size using mouse event.
<html>
<head>
<title>Event handling Examples</title>
</head>
<body>
<center>
<h1 onmouseover="this.style.fontSize='48'";onmouseout="this.style.fontSize='18'";>
Changing the font size move the mouse and see the changes<br><br></h1>
</center>
</body>
</html>

NOTE: that in the preceding example, this.style refers to the style property for the current
element<h1>. The keyword this refers to the current object,
To accept the data from form this.form is used which is referred to the form containing the button.
The onmouseover event handler is a call to compute the given statement.

Using Style Class for Dynamic Changes:-


Not only changing the color image or the background properties but implementing multiple changes at
a single time i.e. Changing the font size color and family on mouse over we use style classes all the
properties are combined with in a single class defined by the user and the class is called with Event
handling methods based of user choice.
A style object is used to enlarge the font and change its color, as shown in the following simple
example.
To implement Style class using event handling methods
<html>
<head>
<title>Event handling Examples</title>
<style type=text/css>
.c1{font-size:85;color:red;font-family:Monotype Corsiva}
.c2{font-size:35;color:blue;font-family:Harlow Solid Italic;border;30}
</style>
</head>
<body>
<center>
<h1 onmouseover="this.className='c1'"onmouseout="this.className='c2'">
Changing the font size move the mouse and see the changes<br><br></h1>
</center>
</body>
</html>

Changing the images on fly:-


Not only changing the color and size of the text but we can also change the image itself in runtime by
using the DOM methods. This can be performed to two methods as specified earlier 1.Event handling
method, 2. script method.
The following example help the user to change the image with event handling methods1
html>
<head><title>Event handling Examples</title></head>
<body>
<center>
<imgsrc="2.jpg" height=500 width=500
onmouseover="this.src='1.jpg'"
onmouseout="this.src='3.jpg'">
</center></body></html>

Example for Onclick

<HTML>
<HEAD>
<script>

function ch()
{
alert ("Welcome to the page")
}
</script>

</HEAD>

<BODY BGCOLOR="NAVYblue">
<h1> Demonstrate on click event<br> Click the below button to get a message<br>
<input type=button value=Click onclick="ch()">

</html>

Example for Onclick


<!DOCTYPE html>
<html>
<body>
<h1>Example for Onload</h1>
<img src="1.jpg" onload="chk()" width="100" height="132">

<script>
function chk() {
alert("Image is loaded");
}
</script>

</body>
</html>

Example for onmousemove, onmouseover, onmouseout

<html>
<head>
<title>Event handling Examples</title>
</head>
<body onmouseover="document.bgColor='red'";
onmousemove="document.bgColor='blue'";
onmouseout="document.bgColor='green'">
<center>

<h1>See the page in red when mouse down<br><br>


And in blue when up<br><br>
In green when clicked is't great!!!!!!!!!!!!!!!<br><br>
</center></body>
</html>

Example for onfocus, onblur, onsubmit)

<html>
<head>
<script>
function chk()
{
x=document.f1.t1.value
if(x=="" || x==" " )
alert("Should not be empty")
}
function pw()
{
alert("Kindly fill in CAPS")
}
function ms()
{
alert("thanks for submission")
}

</script>

</head>
<body>

<h1 align=center> Form event examples</h1>


<form onsubmit="ms()" name=f1>
Enter login id<input type=text name=t1 onblur="chk()"><font
color=red>*</font><br><br>
Enter password<input type=text name=p1 onfocus="pw()"><br><br>

<input type=submit>

</body>
</html>
JAVASCRIPT CLOSURES: JavaScript closures are a fundamental and powerful concept in the
language. A closure allows a function to access its own scope, the scope of the outer function, and the
global scope.
Example:

function Out(outerValue) {
// This inner function has access to the outerValue parameter
function inner(innerValue) {
document.writeln('Outer value:', outerValue);
document,writeln('Inner value:', innerValue);
}

// Return the inner function, forming a closure


return inner;
}
// Create a closure by calling the outer function
var closure = outer('Hello');
// Call the closure, providing an inner value
closure('World');

In the above example:


an outer is defined with outerValue as parameter.
Inside outerFunction, an inner - function is defined that takes a parameter innerValue.
The innerFunction has access to the outerValue due to the closure formed when it was defined within
outerFunction.
the inner-Function returns, effectively creating a closure with access to the outerValue.
Finally, a closure is created by calling outerFunction('Hello'), next the closure with an inner value,
'World'. Is invoked.

JSON

You might also like