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

java

JavaScript is a lightweight, object-based scripting language used for creating dynamic web pages and enhancing interactivity on websites. It was introduced in 1995 and has evolved to support various programming constructs such as functions, loops, and objects. Key features include client-side validation, code reusability through external files, and a variety of built-in methods for strings and arrays.

Uploaded by

danieljeno123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java

JavaScript is a lightweight, object-based scripting language used for creating dynamic web pages and enhancing interactivity on websites. It was introduced in 1995 and has evolved to support various programming constructs such as functions, loops, and objects. Key features include client-side validation, code reusability through external files, and a variety of built-in methods for strings and arrays.

Uploaded by

danieljeno123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Java Script

------------

Introduction

------------

=> JavaScript is designed for beginners and professionals both. JavaScript is used to create client-side
dynamic pages.

=> JavaScript is an object-based scripting language which is lightweight and cross-platform.

=> JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web browser.

What is JavaScript?

-------------------

=> JavaScript (js) is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages.

=> It is an interpreted, full-fledged programming language that enables dynamic interactivity on


websites when applied to an HTML document. It was introduced in the year 1995 for adding programs
to the webpages in the Netscape Navigator browser

=> users can build modern web applications to interact directly without reloading the page every time.
The traditional website uses js to provide several forms of interactivity and simplicity.

History of JavaScript

----------------------

=> the company merged with Sun Microsystems for adding Java into its Navigator so that it could
compete with Microsoft over the web technologies and platforms. Now, two languages were there:Java
and the scripting language.

=>Further, Netscape decided to give a similar name to the scripting language as Java's. It led to
'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of Javascript named 'Mocha'.
Later,

=> the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons and certain
other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From then,
JavaScript came into existence.

Application of JavaScript

-------------------------

JavaScript is used to create interactive websites. It is mainly used for:

=> Client-side validation,


=> Dynamic drop-down menus,

=> Displaying date and time,

=> Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt

dialog box),

=> Displaying clocks etc.

JavaScript Example

-------------------

<script>

document.write("Hello JavaScript by JavaScript");

</script>

code between the body tag

-------------------------

<html>

<body>

<script type="text/javascript">

alert("Hello Apollo");

</script>

</body>

</html>

code between the head tag

-------------------------

<html>

<head>

<script type="text/javascript">

function msg(){

alert("Hello Javatpoint");

</script>
</head>

<body>

<p>Welcome to JavaScript</p>

<form>

<input type="button" value="click" onclick="msg()"/>

</form>

</body>

</html>

External JavaScript file

-------------------------

=> We can create external JavaScript file and embed it in many html page.

=> It provides code reusability because single JavaScript file can be used in several html pages.

=> An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript
files into a single file. It increases the speed of the webpage.

message.js //javascript file

function msg(){

alert("Hello apollo");

index.html // html file

<html>

<head>

<script type="text/javascript" src="message.js"></script>

</head>

<body>

<p>Welcome to JavaScript</p>

<form>

<input type="button" value="click" onclick="msg()"/>

</form>
</body>

</html>

Advantages of External JavaScript

----------------------------------

There will be following benefits if a user creates an external javascript:

=> It helps in the reusability of code in more than one HTML file.

=> It allows easy code readability.

=> It is time-efficient as web browsers cache the external js files, which further reduces the page loading
time.

JavaScript Comment

------------------

=> JavaScript comments are meaningful way to deliver message. It is used to add information about the
code, warnings or suggestions so that end user can easily interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

Advantages of JavaScript comments

-------------------------------------

There are mainly two advantages of JavaScript comments.

=> To make code easy to understand

-> It can be used to elaborate the code so that end user can easily understand the code.

=> To avoid the unnecessary code

-> It can also be used to avoid the code being executed. Sometimes, we add the code to perform some
action. But after sometime, there may be need to disable the code. In such case, it is better to use
comments.

Types of JavaScript Comments

------------------------------

There are two types of comments in JavaScript.

-> Single-line Comment

-> Multi-line Comment

JavaScript Single line Comment


-----------------------------------

It is represented by double forward slashes (//). It can be used before and after the statement.

Example

----------

<html>

<body>

<script>

// It is single line comment

document.write("hello javascript");

</script>

JavaScript Multi line Comment

-------------------------------

It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash. For example:

/* your code here */

<html>

/*<body>

<script>

/* It is multi line comment.

It will not be displayed */

document.write("example of javascript multiline comment");

</script>

</body>*/

</html>

</body>

</html>

JavaScript variable
----------------------

=> A JavaScript variable is simply a name of storage location.

There are some rules while declaring a JavaScript variable (also known as identifiers).

=> Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.

=> After first letter we can use digits (0 to 9), for example value1.

=> JavaScript variables are case sensitive, for example x and X are different variables.

Example

-------

var x = 10;

var _value="Ajay";

Javascript Data Types

---------------------

=> JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.

1.Primitive data type

2.Non-primitive (reference) data type

JavaScript primitive data types

----------------------------------

There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

-----------------------------------------

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types

------------------------------------
The non-primitive data types are as follows:

Data Type Description

------------------------------------

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Operators

---------------------

JavaScript operators are symbols that are used to perform operations on operands. For example:

There are following types of operators in JavaScript.

1.Arithmetic Operators -> +,/, -, %,*, ++ ,--

2.Comparison (Relational) Operators -> == ,!=, >, <, >=,<=

3.Logical Operators -> &&, II, I

4.Assignment Operators -> +=, -= ,/=,*=

JavaScript If-else

----------------------

The JavaScript if-else statement is used to execute the code whether condition is true or false. There are
three forms of if statement in JavaScript.

1.If Statement

Syntex

--------

if(expression){

//content to be evaluated

2.If else statement

Syntex

--------
if(expression){

//content to be evaluated if condition is true

else{

//content to be evaluated if condition is false

3.if else if statement

Syntex

--------

if(expression1){

//content to be evaluated if expression1 is true

else if(expression2){

//content to be evaluated if expression2 is true

else if(expression3){

//content to be evaluated if expression3 is true

else{

//content to be evaluated if no expression is true

JavaScript Switch

------------------

=> The JavaScript switch statement is used to execute one code from multiple expressions.

Syntex

--------

switch(expression){

case value1:
code to be executed;

break;

case value2:

code to be executed;

break;

......

default:

code to be executed if above values are not matched;

/////////////////////////////////////////////////////////////////////

JavaScript Loops

-------------------

=> The JavaScript loops are used to iterate the piece of code using for, while, do while It makes the code
compact.

There are three types of loops in JavaScript.

1.for loop

syntex

---------

for (initialization; condition; increment)

code to be executed

2.while loop

-------------

syntex

---------

intialization;

while (condition)
{

code to be executed

increment/decrement;

3.do-while loop

---------------

syntex

---------

intialization;

do{

code to be executed

increment/decrement;

}while (condition);

JavaScript Functions

---------------------

=> JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.

Advantage of JavaScript function

---------------------------------------

There are mainly two advantages of JavaScript functions.

1.Code reusability: We can call a function several times so it save coding.

2.Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.

JavaScript Function Syntax

--------------------------

function functionName([arg1, arg2, ...argN]){

//code to be executed
}

JavaScript Function Example

----------------------------

<html>

<body>

<script>

function msg(){

alert("hello! this is message");

</script>

<input type="button" onclick="msg()" value="call function"/>

</body>

</html>

JavaScript Function Arguments

===============================

=> We can call function by passing arguments. Let’s see the example of function that has one argument.

example

---------

<html>

<body>

<script>

function getcube(number){

alert(number*number*number);

</script>

<form>

<input type="button" value="click" onclick="getcube(4)"/>

</form>
</body>

</html>

Function with Return Value

===============================

=> We can call function that returns a value and use it in our program. Let’s see the example of

function that returns value.

example

---------

<html>

<body>

<script>

function getInfo(){

return "hello Apollo! How r u?";

</script>

<script>

document.write(getInfo());

</script>

</body>

</html>

JavaScript Function Object

===========================

=> In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the
code globally.

Syntax

----------

new Function ([arg1[, arg2[, ....argn]],] functionBody)

JavaScript Function Methods


----------------------------

Let's see function methods with description.

Method Description

apply() - It is used to call a function contains this value and a single array of arguments.

bind() - It is used to create a new function.

call() - It is used to call a function contains this value and an argument list.

toString() - It returns the result in a form of a string.

example.

=========

<html>

<body>

<script>

var add=new Function("num1","num2","return num1+num2");

document.writeln(add(2,5));

</script>

</body>

</html>

JavaScript Array

------------------

=> JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

- By array literal

- By creating instance of Array directly (using new keyword)

- By using an Array constructor (using new keyword)

1) JavaScript array literal

------------------------------

The syntax of creating array using array literal is given below:


var arrayname=[value1,value2.....valueN];

Example

---------

<html>

<body>

<script>

var emp=["Sonoo","Vimal","Ratan"];

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br/>");

</script>

</body>

</html>

2) JavaScript Array directly (new keyword)

---------------------------------------------

The syntax of creating array directly is given below:

var arrayname=new Array();

Example

---------

<html>

<body>

<script>

var i;

var emp = new Array();

emp[0] = "Arun";

emp[1] = "Varun";

emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");

</script>

</body>

</html>

3) JavaScript array constructor (new keyword)

----------------------------------------------

Example

---------

<html>

<body>

<script>

var emp=new Array("Jai","Vijay","Smith");

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

</body>

</html>

JavaScript String

--------------------

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

- By string literal

- By string object (using new keyword)

1) By string literal

======================

The string literal is created using double quotes. The syntax of creating string using string
literal is given below:

var stringname="string value";

Example

----------

<html>

<body>

<script>

var str="This is string literal";

document.write(str);

</script>

</body>

</html>

2) By string object (using new keyword)

=========================================

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Example

-------

<html>

<body>

<script>

var stringname=new String("hello Apollo string");

document.write(stringname);

</script>

</body>

</html>

JavaScript String Methods

===========================
Let's see the list of JavaScript string methods with examples.

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by searching a
character from the last position.

search() It searches a specified regular expression in a given string and returns its position if a
match occurs.

match() It searches a specified regular expression in a given string and returns that regular
expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the specified starting
position and length.

substring() It is used to fetch the part of the given string on the basis of the specified index.

slice() It is used to fetch the part of the given string. It allows us to assign positive as well
negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current
locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current
locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly created array.

trim() It trims the white space from the left and right side of the string.

1) JavaScript String charAt(index) Method

-------------------------------------------

The JavaScript String charAt() method returns the character at the given index.
Example

----------

<html>

<body>

<script>

var str="javascript";

document.write(str.charAt(2));

</script>

</body>

</html>

2) JavaScript String concat(str) Method

-----------------------------------------

The JavaScript String concat(str) method concatenates or joins two strings.

Example

----------

<html>

<body>

<script>

var s1="Apollo ";

var s2="computer center";

var s3=s1+s2;

document.write(s3);

</script>

</body>

</html>

JavaScript Objects

-------------------
=> A javaScript object is an entity having state and behavior (properties and method). For example: car,
pen, bike, chair, glass, keyboard, monitor etc.

=> JavaScript is an object-based language. Everything is an object in JavaScript.

=> JavaScript is template based not class based. Here, we don't create class to get the object. But, we
direct create objects.

Creating Objects in JavaScript

--------------------------------

There are 3 ways to create objects.

1.By object literal

2.By creating instance of Object directly (using new keyword)

3.By using an object constructor (using new keyword)

1) JavaScript Object by object literal

-----------------------------------------

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

Example

----------

<html>

<body>

<script>

emp={id:102,name:"Shyam Kumar",salary:40000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

</body>

</html>

2) By creating instance of Object

------------------------------------
The syntax of creating object directly is given below:

var objectname=new Object();

Example

--------

<html>

<body>

<script>

var emp=new Object();

emp.id=101;

emp.name="Ravi Malik";

emp.salary=50000;

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

</body>

</html>

3) By using an Object constructor

-------------------------------------

=> Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.

Example

--------

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;
}

e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>

Defining method in JavaScript Object

---------------------------------------

We can define method in JavaScript object. But before defining method, we need to add property in the
function with same name as method.

Example

--------

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

this.changeSalary=changeSalary;

function changeSalary(otherSalary){

this.salary=otherSalary;

e=new emp(103,"Sonoo Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

e.changeSalary(45000);

document.write("<br>"+e.id+" "+e.name+" "+e.salary);


</script>

</body>

</html>

JavaScript Events

------------------

=> The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser.

=> When javascript code is included in HTML, js react over these events and allow the execution. This
process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event
Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

Mouse events:

==============

Event Performed Event Handler Description

=============== ============= =============

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Click Event

-----------
Example

-------

<html>

<head> Javascript Events </head>

<body>

<script language="Javascript" type="text/Javascript">

<!--

function clickevent()

document.write("Apollo computer education");

//-->

</script>

<form>

<input type="button" onclick="clickevent()" value="Who's this?"/>

</form>

</body>

</html>

mouseover Event

----------------

<html>

<body>

<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="ja1.jpg" alt="Java"


width="32" height="32">

<p>The function bigImg() is triggered when the user moves the mouse pointer over the image.</p>

<p>The function normalImg() is triggered when the mouse pointer is moved out of the image.</p>

<script>

function bigImg(x) {
x.style.height = "64px";

x.style.width = "64px";

function normalImg(x) {

x.style.height = "32px";

x.style.width = "32px";

</script>

</body>

</html>

mouseout Event

----------------

<html>

<body>

<p>This example demonstrates how to assign an "onmouseover" and "onmouseout" event to a h1


element.</p>

<h1 id="demo" onmouseover="mouseOver()" onmouseout="mouseOut()">Mouse over me</h1>

<script>

function mouseOver() {

document.getElementById("demo").style.color = "red";

function mouseOut() {

document.getElementById("demo").style.color = "black";

</script>

</body>

</html>

mousedown and up event


-----------------------

<html>

<body>

<p id="myP" onmousedown="mouseDown()" onmouseup="mouseUp()">

Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this
paragraph, and sets the color of the text to red. The mouseUp() function is triggered when the mouse
button is released, and sets the color of the text to green.

</p>

<script>

function mouseDown() {

document.getElementById("myP").style.color = "red";

function mouseUp() {

document.getElementById("myP").style.color = "green";

</script

</body>

</html>

mouse move event

-----------------

<html>

<head>

<style>

div {

width: 200px;

height: 100px;

border: 1px solid black;

}
</style>

</head>

<body>

<div onmousemove="myFunction(event)" onmouseout="clearCoor()"></div>

<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>

<p>When the mouse is moved over the div, the p element will display the horizontal and vertical
coordinates of your mouse pointer, whose values are returned from the clientX and clientY properties
on the

MouseEvent object.</p>

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

<script>

function myFunction(e) {

var x = e.clientX;

var y = e.clientY;

var coor = "Coordinates: (" + x + "," + y + ")";

document.getElementById("demo").innerHTML = coor;

function clearCoor() {

document.getElementById("demo").innerHTML = "";

</script>

</body>

</html>

JavaScript BOM

---------------

Browser Object Model

------------------------

The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by specifying
window or directly.

For example:

window.alert("hello apollo");

is same as:

alert("hello apollo");

Window

------

Diffrent components

1, Document

2, History

3, Screen

4, Navigator

Window Object

==============

=> The window object represents a window in browser. An object of window is created automatically by
the browser.

=> Window is the object of browser, it is not the object of javascript. The javascript objects are string,
array, date etc.

Methods of window object

=========================

The important methods of window object are as follows:

Method Description

------- ------------

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.


setTimeout() performs action after specified time like calling function, evaluating expressions etc.

Example of alert() in javascript

----------------------------------

It displays alert dialog box. It has message and ok button.

<html>

<body>

<script type="text/javascript">

function msg(){

var v= prompt("Who are you?");

alert("I am "+v);

</script>

<input type="button" value="click" onclick="msg()"/>

</body>

</html>

Example of Confirm() in javascript

----------------------------------

<html>

<body>

<script type="text/javascript">

function msg(){

var v= confirm("Are u sure?");

if(v==true){

alert("ok");

else{

alert("cancel");

}
}

</script>

<input type="button" value="delete record" onclick="msg()"/>

</body>

</html>

JavaScript History Object

------------------------

=> The JavaScript history object represents an array of URLs visited by the user. By using this object, you
can load previous, forward or any particular page.

The history object is the window property, so it can be accessed by:

window.history

Property of JavaScript history object

There are only 1 property of history object.

No. Property Description

---- -------- -----------

1 length returns the length of the history URLs.

Methods of JavaScript history object

---------------------------------------

There are only 3 methods of history object.

No. Method Description

---- ----- ------------

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

Example of history object

---------------------------

Let s see the different usage of history object.

history.back();//for previous page


history.forward();//for next page

history.go(2);//for next 2nd page

history.go(-2);//for previous 2nd page

//////////////////////////////////////////

<html>

<head>

<title>Apollo computer education</title>

</head>

<body>

<b>Press the back button</b>

<input type="button" value="Back" onclick="previousPage()">

<script>

function previousPage() {

window.history.back();

}S

</script>

</body>

</html>

JavaScript Navigator Object

----------------------------

=> The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:

window.navigator

Property of JavaScript navigator object

-----------------------------------------

There are many properties of navigator object that returns information of the browser.

No. Property Description


--- ------- -------------

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false

5 userAgent returns the user agent

6 language returns the language. It is supported in Netscape and Firefox only.

7 userLanguage returns the user language. It is supported in IE only.

8 plugins returns the plugins. It is supported in Netscape and Firefox only.

9 systemLanguage returns the system language. It is supported in IE only.

10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.

11 platform returns the platform e.g. Win32.

12 online returns true if browser is online otherwise false.

Example of navigator object

---------------------------------

Let s see the different usage of history object.

<html>

<body>

<h2>JavaScript Navigator Object</h2>

<script>

document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);

document.writeln("<br/>navigator.appName: "+navigator.appName);

document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);

document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);

document.writeln("<br/>navigator.language: "+navigator.language);

document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);

document.writeln("<br/>navigator.platform: "+navigator.platform);

document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>

</body>

</html>

JavaScript Screen Object

==========================

=> The JavaScript screen object holds information of browser screen. It can be used to display screen
width, height, colorDepth, pixelDepth etc.

The screen object is the window property, so it can be accessed by:

window.screen

Property of JavaScript Screen Object

----------------------------------------

There are many properties of screen object that returns information of the browser.

No. Property Description

-- -------- --------------

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.

Example of JavaScript Screen Object

=============================================

Let s see the different usage of screen object.

<html>

<body>

<script>

document.writeln("<br/>screen.width: "+screen.width);

document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);

document.writeln("<br/>screen.availHeight: "+screen.availHeight);

document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);

document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);

</script>

</body>

</html>

JavaScript DOM

---------------

The document object represents the whole html document.

=>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 html document is loaded in the browser, it becomes a document object. It is the root element
that represents the html document. It has properties and methods.

=> By the help of document object, we can add dynamic content to our web page.

As mentioned earlier, it is the object of window. So

window.document Is same as document

Properties of document object

------------------------------

Let's see the properties of document object that can be accessed and modified by the document object.
- text

- textarea

anchor - checkbox

- radio

document form ---------->- select - Option

- reset

link - button

Methods of document object

============================

We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

------- -----------

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the
end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object


------------------------------------------

In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

-----

name is the attribute name of the input text.

-----

value is the property, that returns the value of the input text.

------

Let's see the simple example of document object that prints name with welcome message.

<html>

<head>

<title>Apollo computer education</title>

</head>

<body>

<script type="text/javascript">

function printvalue(){

var name=document.form1.name.value;

alert("Welcome: "+name);

</script>

<form name="form1">

Enter Name:<input type="text" name="name"/>


<input type="button" onclick="printvalue()" value="print name"/>

</form>

</body>

</html>

Javascript - document.getElementById() method

=====================================================

The document.getElementById() method returns the element of specified id.

In the previous topic, we have used document.form1.name.value to get the value of the input value.
Instead of this, we can use document.getElementById() method to get value of the input text. But we
need to define id for the input field.

Let's see the simple example of document.getElementById() method that prints cube of the given
number.

<html>

<head>

<title>Apollo computer education</title>

</head>

<body>

<script type="text/javascript">

function getcube(){

var number=document.getElementById("number").value;

alert(number*number*number);

</script>

<form>
Enter No:<input type="text" id="number" name="number"/><br/>

<input type="button" value="cube" onclick="getcube()"/>

</form>

</form>

</body>

</html>

Javascript - document.getElementsByName() method

=================================================

=> The document.getElementsByName() method returns all the element of specified name.

The syntax of the getElementsByName() method is given below:

document.getElementsByName("name")

Here, name is required.

Example :

---------

<html>

<head>

<title>Apollo computer education</title>

</head>

<body>

<script type="text/javascript">

function totalelements()

var allgenders=document.getElementsByName("gender");

alert("Total Genders:"+allgenders.length);

</script>

<form>
Male:<input type="radio" name="gender" value="male">

Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">

</form>

</body>

</html>

Javascript - document.getElementsByTagName() method

====================================================

=> The document.getElementsByTagName() method returns all the element of specified tag name.

The syntax of the getElementsByTagName() method is given below:

document.getElementsByTagName("name")

Here, name is required.

Example :1

---------

<html>

<head>

<title>Apollo computer education</title>

</head>

<body>

<script type="text/javascript">

function countpara(){

var totalpara=document.getElementsByTagName("p");

alert("total p tags are: "+totalpara.length);

</script>

<p>This is a pragraph</p>

<p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>

<p>Let's see the simple example</p>


<button onclick="countpara()">count paragraph</button>

</body>

</html>

Example :2

-----------

<html>

<head>

<title>Apollo computer education</title>

</head>

<body>

<script type="text/javascript">

function counth2(){

var totalh2=document.getElementsByTagName("h2");

alert("total h2 tags are: "+totalh2.length);

function counth3(){

var totalh3=document.getElementsByTagName("h3");

alert("total h3 tags are: "+totalh3.length);

</script>

<h2>This is h2 tag</h2>

<h2>This is h2 tag</h2>

<h3>This is h3 tag</h3>

<h3>This is h3 tag</h3>

<h3>This is h3 tag</h3>

<button onclick="counth2()">count h2</button>

<button onclick="counth3()">count h3</button>

</body>
</html>

Javascript - innerHTML

========================

=> The innerHTML property can be used to write the dynamic html on the html document.

=> It is used mostly in the web pages to generate the dynamic html such as registration form, comment
form, links etc.

Example of innerHTML property

In this example, we are going to create the html form when user clicks on the button.

<html>

<body>

<script type="text/javascript" >

function showcommentform() {

var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea rows='5'


cols='50'></textarea><br><input type='submit' value='comment'>";

document.getElementById('mylocation').innerHTML=data;

</script>

<form name="myForm">

<input type="button" value="comment" onclick="showcommentform()">

<div id="mylocation"></div>

</form>

</body>

</html>

Show/Hide Comment Form Example using innerHTML

--------------------------------------------------

<!DOCTYPE html>

<html>

<head>
<title>First JS</title>

<script>

var flag=true;

function commentform(){

var cform="Name:<br><input type='text' name='name'><br>Comment:<br><textarea rows='5'


cols='50'></textarea><br><input type='submit' value='comment'>";

if(flag){

document.getElementById("mylocation").innerHTML=cform;

flag=false;

}else{

document.getElementById("mylocation").innerHTML="";

flag=true;

</script>

</head>

<body>

<input type ="button" value="Comment" onclick="commentform()">

<div id="mylocation"></div>

</body>

</html>

Javascript - innerText

=========================

=> The innerText property can be used to write the dynamic text on the html document. Here, text will
not be interpreted as html text but a normal text.

=> It is used mostly in the web pages to generate the dynamic content such as writing the validation
message, password strength etc.

Javascript innerText Example

=============================
In this example, we are going to display the password strength when releases the key after press.

<html>

<body>

<script type="text/javascript" >

function validate() {

var msg;

if(document.myForm.userPass.value.length>5){

msg="good";

else{

msg="poor";

document.getElementById('mylocation').innerText=msg;

</script>

<form name="myForm">

<input type="password" value="" name="userPass" onkeyup="validate()">

Strength:<span id="mylocation">no strength</span>

</form>

</body>

</html>

JavaScript Form Validation

----------------------------

=> It is important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.

=> JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.
=> Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

JavaScript Form Validation Example

--------------------------------------

In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.

<html>

<body>

<script>

function validateform(){

var name=document.myform.name.value;

var password=document.myform.password.value;

if (name==null || name==""){

alert("Name can't be blank");

return false;

}else if(password.length<6){

alert("Password must be at least 6 characters long.");

return false;

</script>

<body>

<form name="myform" method="post" action="http://www.apollcekrishnagiri.com" onsubmit="return


validateform()" >

Name: <input type="text" name="name"><br/>

Password: <input type="password" name="password"><br/>


<input type="submit" value="register">

</form>

</body>

</html>

JavaScript Retype Password Validation

-------------------------------------

<html>

<head>

<script type="text/javascript">

function matchpass(){

var firstpassword=document.f1.password.value;

var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){

return true;

else{

alert("password must be same!");

return false;

</script>

</head>

<body>

<form name="f1" action="http://www.apollokrishnagiri.com" onsubmit="return matchpass()">

Password:<input type="password" name="password" /><br/>

Re-enter Password:<input type="password" name="password2"/><br/>


<input type="submit">

</form>

</body>

</html>

JavaScript Number Validation

-----------------------------

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<html>

<head>

<script>

function validate(){

var num=document.myform.num.value;

if (isNaN(num)){

document.getElementById("numloc").innerHTML="Enter Numeric value only";

return false;

}else{

return true;

</script>

</head>

<body>

<form name="myform" action="http://www.apollokrishnagiri.com" onsubmit="return validate()" >

Number: <input type="text" name="num"><span id="numloc"></span><br/>

<input type="submit" value="submit">

</form>

</body>

</html>
JavaScript validation with image

----------------------------------

Let’s see an interactive JavaScript form validation example that displays correct and incorrect image if
input is correct or incorrect.

<html>

<body>

<script type="text/javascript">

function validate(){

var name=document.f1.name.value;

var passwordlength=document.f1.password.value.length;

var status=false;

if(name==""){

document.getElementById("namelocation").innerHTML=

" <img src='D:\ja1.jpg'/> Please enter your name";

status=false;

}else{

document.getElementById("namelocation").innerHTML=" <img src='D:\ja1.jpg'/>";

status=true;

if(passwordlength<6){

document.getElementById("passwordlocation").innerHTML=

" <img src='D:\ja1.jpg'/> Password must be greater than 6";

status=false;

}else{

document.getElementById("passwordlocation").innerHTML=" <img src='D:\ja1.jpg'/>";

return status;

}
</script>

<form name="f1" action="http://www.apollokrishnagiri.com" onsubmit="return validate()">

<table>

<tr><td>Name:</td><td><input type="text" name="name"/>

<span id="namelocation" style="color:red"></span></td></tr>

<tr><td>Password:</td><td><input type="password" name="password"/>

<span id="passwordlocation" style="color:red"></span></td></tr>

<tr><td colspan="2"><input type="submit" value="register"/> </td></tr>

</table>

</form>

</body>

</html>

JavaScript email validation

------------------------------

-> We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

-email id must contain the @ and . character

-There must be at least one character before and after the @.

-There must be at least two characters after . (dot).

-Let's see the simple example to validate the email field.

example

----------

<html>

<body>

<script>

function validateemail()

var x=document.myform.email.value;
var atposition=x.indexOf("@");

var dotposition=x.lastIndexOf(".");

if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){

alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);

return false;

</script>

<body>

<form name="myform" method="post" action="http://www.apollokrishnagiri.com" onsubmit="return


validateemail();">

Email: <input type="text" name="email"><br/>

<input type="submit" value="register">

</form>

</body>

</html>

JavaScript Debugging

=====================

=> Sometimes a code may contain certain mistakes. Being a scripting language, JavaScript didn't show
any error message in a browser. But these mistakes can affect the output.

=> The best practice to find out the error is to debug the code. The code can be debugged easily by using
web browsers like Google Chrome, Mozilla Firebox.

JavaScript Debugging Example

==============================

=> Here, we will find out errors using built-in web browser debugger. To perform debugging, we can use
any of the following approaches:

- > Using console.log() method


- > Using debugger keyword

The console.log() method displays the result in the console of the browser. If there is any mistake in the
code, it generates the error message.

Example

--------

<html>

<title>My Debugging</title>

<body>

<script>

x = 10;

y = 15;

z = x + y;

console.log(z);

console.log(a);//a is not intialized

</script>

</body>

</html>

Using debugger keyword

---------------------------

=> In debugging, generally we set breakpoints to examine each line of code step by step.

=> There is no requirement to perform this task manually in JavaScript.

=> JavaScript provides debugger keyword to set the breakpoint through the code itself.

=> The debugger stops the execution of the program at the position it is applied.

Now, we can start the flow of execution manually.

=> If an exception occurs, the execution will stop again on that particular line.

example

---------

<html>
<body>

<h2>JavaScript Debugger</h2>

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

<p>With the debugger turned on, the code below should stop executing before it executes the third
line.</p>

<script>

let x = 15 * 5;

debugger;

document.getElementById("demo").innerHTML = x;

</script>

</body>

</html>

JavaScript Hoisting

-------------------

=> Hoisting is a mechanism in JavaScript that moves the declaration of variables and functions at the
top. So, in JavaScript we can use variables and functions before declaring them.

=> JavaScript hoisting is applicable only for declaration not initialization. It is required to initialize the
variables and functions before using their values.

Hoisting Example

----------------

<html>

<title>My Hoisting</title>

<body>

<script>

x=10;

document.write(x);

var x;
</script>

</body>

</html>

JavaScript Function Hoisting

------------------------------

Let's see the simple example of variable hoisting.

<html>

<title>My Hoisting</title>

<body>

<script>

document.write(sum(10,20));

function sum(a,b)

return a+b;

</script>

</body>

</html>

JavaScript Strict Mode

-------------------------

=> Being a scripting language, sometimes the JavaScript code displays the correct result even it has
some errors. To overcome this problem we can use the JavaScript strict mode.

=> The JavaScript provides "use strict"; expression to enable the strict mode. If there is any silent error
or mistake in the code, it throws an error.

Console.Log Example
--------------

<html>

<body>

<script>

x=10;

console.log(x);

</script>

</body>

</html>

strict Example

-----------------

<html>

<title>My Strict</title>

<body>

<script>

console.log(sum(10,20));

function sum(a,a)

"use strict";

return a+a;

</script>

</body>

</html>

You might also like