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.
Example
<html>
<body>
<h2>Welcome
to JavaScript</h2>
<script>
document.write("Hello
JavaScript by JavaScript");
</script>
</body>
</html>
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.
<html>
<body>
<script>
//
It is single line comment
document.write("hello
javascript");
</script>
</body>
</html>
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:
<html>
<body>
<script>
/*
It is multi line comment.
It
will not be displayed */
document.write("example
of javascript multiline comment");
</script>
</body>
</html>
JavaScript Variable
A JavaScript
variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.
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.
<html>
<body>
<script>
var
x = 10;
var
y = 20;
var
z=x+y;
document.write(z);
</script>
</body>
</html>
JavaScript
local variable
A
JavaScript local variable is declared inside block or function. It is
accessible within the function or block only For example:
JavaScript
global variable
A JavaScript
global variable is accessible from any function. A variable i.e. declared
outside the function or declared with window object is known as global
variable. For example:
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a
global variable
function checkscope( )
{
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
Functions:-
Predefined(Built-in)Functions
Number()-Converts an object's value to a number
<html>
<body>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction()
{
var x1 = true;
var n = Number(x1);
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
String()-Converts an object's value to a string
<html>
<body>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction() {
var x1 = Boolean(0);
var x4 = "12345";
var res =
String(x1) + "<br>" + String(x4) + "<br>"
;
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
isNaN() :- Determines whether a value is
an illegal number
<html>
<body>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction()
{
var res = "";
res = res + isNaN(123) + ": 123<br>";
res = res + isNaN('Hello') + ": 'Hello'<br>";
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
false:
123
true:
'Hello'
parseFloat() :- Parses a string and returns a
floating point number.
<html>
<body>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction()
{
var a = parseFloat("10")
document.getElementById("demo").innerHTML = a +
"<br>" ;
}
</script>
</body>
</html>
parseInt() function parses a string and
returns an integer
<html>
<body>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction()
{
var a = parseInt("10")
document.getElementById("demo").innerHTML = a +
"<br>" ;
}
</script>
</body>
</html>
eval():-function evaluates or executes an
argument.
<html>
<body>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction()
{
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
document.getElementById("demo").innerHTML = a;
}
</script>
</body>
</html>
Userdefined Functions:-
Example:-
<html>
<head>
<script
type="text/javascript" >
function
display()
{
document.write("Hello
there");
}
display();
</script>
</head>
</html>
Example:-
<html>
<head>
<script
type="text/javascript" >
function
add(x,y)
{
return
(x+y);
}
</script>
</head>
<body>
<script
type="text/javascript">
var
x=add(12,12);
document.write("Addition
is " + x);
</script>
</body>
</html>
DOM Objects:-
Each
HTML document that gets loaded into a window becomes a document object. The
document contains the contents of the page.
The
document object contains all information of the current window.
Property
|
Description
|
Title
|
Sets
or returns the title of the document
|
URL
|
Returns
the full URL of the document
|
Domain
|
Returns
the domain name of the server that loaded the document.
|
Methods of Document Object:
1. write(“string”): writes
the given string on the document.
2. getElementById(): returns
the element having the given id value.
3. getElementsByName(): returns
all the elements having the given name value.
4. getElementsByTagName(): returns
all the elements having the given tag name.
5. getElementsByClassName(): returns
all the elements having the given class name.
Example:-
<html>
<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>
</body>
</html>
The Element Object
In
the HTML DOM, the Element object represents an HTML element, like P, DIV, A,
TABLE, or any other HTML element.
Properties
and Methods
The
following properties and methods can be used on all HTML elements:
Blur():-Removes
focus from an element.
focus() method
is used to give focus to an element (if it can be focused).
<html>
<head></head>
<body>
<p
id="myAnchor">Hello</p>
<input
type="button" onclick="getfocus()" value="Get
focus">
<input
type="button" onclick="losefocus()" value="Lose
focus">
<script>
function
getfocus()
{
document.getElementById("myAnchor").focus();
}
function
losefocus()
{
document.getElementById("myAnchor").blur();
}
</script>
</body>
</html>
Click():-Simulates a mouse click on an element.
<html>
<body>
<form>
<input
type="checkbox" id="myCheck" onmouseover="myFunction()"
onclick="alert('click event occured')">
</form>
<script>
function
myFunction()
{
document.getElementById("myCheck").click();
}
</script>
</body>
</html>
innerHTML property
sets or returns the HTML content (inner HTML) of an element.
<html>
<body>
<p
id="demo" onclick="myFunction()">Click me to change my
HTML content (innerHTML).</p>
<script>
function
myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph
changed!";
}
</script>
</body>
</html>
Anchor Object
href :- property sets or returns the value
of the href attribute of a link.
rel:- property sets or returns the value of
the rel attribute of a link.
name:-Sets or returns the value of the name
attribute of a link.
<html>
<body>
<p>Welcome
to
<a
href = "https://www.foresight.com/"
id="GFG">Hello</a>
</p>
<button
onclick = "myGeeks()">Submit</button>
<p
id = "sudo"></p>
<script>
function
myGeeks()
{
var
x = document.getElementById("GFG").href;
document.getElementById("sudo").innerHTML
= x;
}
</script>
</center>
</body>
</html>
Form Object
The
Form object represents an HTML <form> element.
Method
reset() method resets the values of all
elements in a form (same as clicking the Reset button).
submit() method submits the form (same as
clicking the Submit button).
Example1
<html>
<body>
<form
id="myForm">
First
name: <input type="text" name="fname"><br>
Last
name: <input type="text"
name="lname"><br><br>
<input
type="button" onclick="myFunction()" value="Reset
form">
</form>
<script>
function
myFunction()
{
document.getElementById("myForm").reset();
}
</script>
</body>
</html>
Example2
<html>
<body>
<form
name="f1" id="myForm" action="/a.php">
First
name: <input type="text" name="fname"><br>
Last
name: <input type="text"
name="lname"><br><br>
<input
type="button" onclick="myFunction()" value="Submit
form">
</form>
<script>
function
myFunction()
{
document.getElementById("myForm").submit();
}
</script>
</body>
</html>
Form Object Properties
action
:-property sets or returns the value of the action attribute in a form.
The
action attribute specifies where to send the form data when a form is
submitted.
name:-set
or returns the value of the name attribute in a form
Hidden Object
The
Input Hidden object in HTML DOM represents the <input> element with type
= “hidden” attribute. The element can be accessed by using getElementById()
method.
Property Values:
•defaultvalue:
It is used to set or return the default value of a hidden input field.
•form:
It returns the reference of form that contains the hidden input field.
•name:
It is used to set or return the name attribute value of a hidden input field.
•type:
It returns the type of form element the hidden input field belongs.
•value:
It is used to set or return the value of the value attribute of a hidden input
field.
<html>
<body>
<input
type = "hidden" id = "a" value="hi">
<button
onclick = "Geeks()">Submit </button>
<p
id = "sudo"></p>
<script>
function
Geeks()
{
var
g = document.getElementById("a").value;
document.getElementById("sudo").innerHTML
= g;
}
</script>
</body>
</html>
Password Object
The
Input Password Object in HTML DOM is used to represent an HTML input element
with type=”password”.
The
input element with type=”password” can be accessed by using getElementById()
method.
syntax:
It
is used to access input type=”password”
document.getElementById("id");
It
is used to create type=”password” element.
document.createElement("input");
Object Properties:
type:-This
property is used to return which type of form element the password field is.
value:-This
property is used to set or return the value of the value attribute of a
password field.
form:-This
property is used to return reference to the form that contains the password
field.
maxLength:-This
property is used to set or return the value of the maxlength attribute of a
password field.
name:-This
property is used to set or return the value of the name attribute of a password
field.
readOnly:-This
property is used to set or return whether the password field is read-only or
not.
size:-This
property is used to set or return the value of the value attribute of the
password field.
Input
Number Object Methods:
select():
This is used to select the content of a password field.
Checkbox Object
The
Input Checkbox object represents an HTML <input> element with
type="checkbox".
Access
an Input Checkbox Object
You
can access an <input> element with type="checkbox" by using
getElementById():
type property
returns which type of form element the checkbox is.
var
x = document.getElementById("myCheck").type;
value property
sets or returns the value of the value attribute of a checkbox.
var
x = document.getElementById("myCheck").value;
name property
sets or returns the value of the name attribute of a checkbox.
var
x = document.getElementById("myCheck").name;
form property
returns a reference to the form containing the checkbox.
var
x = document.getElementById("myCheck").form.id;
<html>
<body>
<input
type="checkbox" onclick="myFunction()"
id="myCheck">
<p
id="demo"></p>
<script>
function
myFunction()
{
var
x = document.getElementById("myCheck").type;
document.getElementById("demo").innerHTML
= x;
}
</script>
</body>
</html>
Select Object
The
Select object in HTML DOM is used to represent an HTML <select> element.
The <select> element can be created by using the document.createElement()
method and it can be accessed using the getElementById().
Syntax:
•It
is used to create <select> element.
document.createElement("SELECT")
•It
is used to access <select> element.
document.getElementById("mySelect")
Select
Object Properties:
•disabled:
It is used to set or return whether the drop-down list is disabled, or not.
•form:
It returns the reference to the form that contains the drop-down list.
•length:It
returns the number of <option> elements in a drop-down list.
•multiple:
It is used to set or return whether more than one option can be selected from
the drop-down list.
•name:
It is used to set or return the value of the name attribute of a drop-down
list.
•size:
It is used to set or return the value of the size of a drop-down list.
•type:
It returns the type of form element a drop-down list.
•value:It
is used to set or return the value of selected option in a drop-down list.
Select
Object Methods:
•add():
It is used to add an option to a drop-down list.
•checkValidity():
It is used to check the validity of a drop-down list.
•remove():
It is used to remove an option from a drop-down list.
<html>
<body>
<select
id="a">
<option>Fork
Python</option>
<option>Fork
Java</option>
<option>Fork
CPP</option>
<option>Sudo
Placement</option>
</select>
<button
onclick = "myGeeks()"> Create Select Element </button>
<p
id="test"></p>
<script>
function
myGeeks()
{
var
len = document.getElementById("a").length;
document.getElementById("test").innerHTML
= len;
}
</script>
</body>
</html>
Option Object
The
Option object represents an HTML <option> element.
Access
an Option Object
You
can access an <option> element by using getElementById():
Option
Object Properties
disabled property
sets or returns whether an option in a drop-down list should be disabled, or
not.
var
x = document.getElementById("pets").options[2].disabled = true;
form property
returns a reference to the form that contains an option.
var
x = document.getElementById("apple").form.id;
selected property
sets or returns the selected state of an option.
document.getElementById("orange").selected
= true;
text property
sets or returns the text of an option element.
document.getElementById("apple").text
= "newTextForApple";
value property
sets or returns the value of the option
(the
value to be sent to the server when the form is submitted).
document.getElementById("myOption").value
= "newValue";
<html>
<body>
<select
id="pets" size="3">
<option>Cat</option>
<option>Dog</option>
<option>Horse</option>
</select>
<button
onclick="myFunction()">Disable Option</button>
<script>
function
myFunction()
{
var
x = document.getElementById("pets").options[2].disabled = true;
}
</script>
</body>
</html>
Radio Object
The
Input Radio object represents an HTML <input> element with
type="radio".
Input
Radio Object Properties
value property
sets or returns the value of the value attribute of the radio button.
var
x = document.getElementById("myRadio").value;
type property
returns which type of form element a radio button is.
var
x = document.getElementById("myRadio").type;
name
property sets or returns the value of the name attribute of a radio button.
var
x = document.getElementById("myRadio").name;
form property
returns a reference to the form that contains the radio button
var
x = document.getElementById("myCheck").form.id;
disabled property
sets or returns whether a radio button should be disabled, or not.
document.getElementById("cats").disabled
= true;
<body>
<input
type="radio" name="colors" value="red"
id="myRadio">Red<br>
<button
onclick="myFunction()">Try it</button>
<p
id="demo"></p>
<script>
function
myFunction()
{
var
x = document.getElementById("myRadio").name;
document.getElementById("demo").innerHTML
= x;
}
</script>
</body>
</html>
Text object
The
Text object represents the textual content of an element or attribute.
Property
Value:-
sets or returns the value of the text field
defaultvalue:-
sets or returns the default value of the text field
name:-
sets or returns the value of the name of the text field
size:-
sets or returns the width of the text field
Methods:-
Select():-
selects the contents of a text field.
Focus():-sets
focus to the current window
Blur():-Removes
focus from the current window.
Syntax:
•It
is used to access input text object.
document.getElementById("id");
•It
is used to create input element.
document.createElement("input");
<html>
<body>
<input
type="text" id="text_id" value="Hello Geeks!">
<button
onclick="myGeeks()">Click Here!</button>
<p
id="GFG"></p>
<script>
function
myGeeks()
{
var
txt = document.getElementById("text_id").value;
document.getElementById("GFG").innerHTML
= txt;
}
</script>
</body>
</html>
Textarea Object
The
Textarea Object in HTML DOM is used to represent the HTML <textarea>
Element. The textarea element can be accessed by using getElementById() method.
Syntax:
document.getElementById("ID");
Where
ID is assigned to the <textarea> element.
Property
Values:
•cols:
It is used to set or return the value of ths cols attribute of a textarea
Element.
•defaultvalue:
It is used to set or return the defaultvalue of the textarea element.
•form:
It is used to return the reference of the form that contains the textarea
field.
•maxLength:
It is used to set or return the value of the maxattribute of a textarea field.
•name:
It is used to set or return the name attribute of a textarea field.
•readOnly:
It is used to return the value of the readonly attribute of a textarea field.
•type:
rows: It is used to set or return the value of the type attribute of a
textareafield
•value:
It is used to set or return the content of a textarea field.
Methods:
•select():
It is used to select all the entire contents present in the textarea field.
<html>
<body>
<textarea
id = "a"> welcome</textarea>
<button
onclick = "Geeks()">Submit </button>
<p
id = "sudo"></p>
<script>
function
Geeks()
{
var
x = document.getElementById("myGeeks").value;
document.getElementById("sudo").innerHTML
= x;
}
</script>
</body>
</html>
Frame Object
Frame
object represents an HTML frame which defines one particular window(frame)
within a frameset.
It
defines the set of frame that make up the browser window.
It
is a property of the window object.
It
defines a particular area in which another HTML document can be displayed.
A
frame should be used within a <FRAMESET> tag.
<FRAME>
Tag Attributes
src :-
It is used to give the file name that should be located in the frame. Its value
can be any URL.
For
example: src= “/html/abc.html”
name:-It
allows you to give a name to a frame. This attribute is used to indicate that a
document should be loaded into a frame.
frameborder:-It
specifies whether or not the borders of that frame are shown. This attribute
overrides the value given in the frameborder attribute on the tag if one is
given. This can take values either 1 (Yes) or 0 (No).
marginwidth
:-It allows you to specify the width of the space between the left and right of
the frame's border and the content. The value is given in pixels.
For
example: marginwidth = “10”.
marginheight:-It
allows you to specify the height of the space between the top and bottom of the
frame's borders and its contents. The value is given in pixels.
For
example: marginheight = “10”.
noresize:-By
default, you can resize any frame by clicking and dragging on the borders of a
frame. It prevents a user from being able to resize the frame.
For
example: noresize = “noresize”.
scrolling:-It
controls the appearance of the scrollbars that appear on the frame. It takes
values either “Yes”, “No” or “Auto”.
For
example: scrolling = “no” means it should not have scroll bars.
Link Object
The
Link object represents an HTML <link> element.
Access
a Link Object
You
can access a <link> element by using getElementById():
href property
sets or returns the URL of a linked document.
var
x = document.getElementById("myLink").href;
rel property
sets or returns a space-separated list that defines the relationship between
the current document and the linked document.
var
x = document.getElementById("myLink").rel;
sizes property
returns the value of the sizes attribute of the linked resource.
var
x = document.getElementById("myLink").sizes;
type property
sets or returns the content type (MIME type) of the linked document.
var
x = document.getElementById("myLink").type;
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
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.
Properties;-
length:-returns
the number of frames in a window
location:-returns
the location object for the window
name:-sets
or returns the name of window
innerHeight:-sets
or returns the inner height of a windows content area.
innerWidth:-sets
or returns the inner width of a windows content area.
outerHeight:-
sets or returns the outer height of a windows content area.
outerWidth:-
sets or returns the outer width of a windows content area.
Example
of alert() in javascript
It
displays alert dialog box. It has message and ok button.
<html>
<body>
<script
type="text/javascript">
function
msg()
{
alert("Hello
Alert Box");
}
</script>
<input
type="button" value="click" onclick="msg()"/>
</body>
</html>
Example
of confirm() in javascript
It
displays the confirm dialog box. It has message with ok and cancel buttons.
<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>
Example
of prompt() in javascript
It
displays prompt dialog box for input. It has message and textfield.
<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 open() in javascript
It
displays the content in a new window.
<html>
<body>
<script
type="text/javascript">
function
msg()
{
open("http://www.google.com");
}
</script>
<input
type="button" value="jt" onclick="msg()"/>
</body>
</html>
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.
Property
of JavaScript navigator object
appName:-
returns the name
appVersion:-
returns the version
appCodeName:-
returns the code name
userAgent:-
returns the user agent
Methods
of JavaScript navigator object
javaEnabled():-checks
if java is enabled.
taintEnabled():-checks
if taint is enabled.
<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.userAgent:
"+navigator.userAgent);
</script>
</body>
</html>
History
object
The
window.history object contains the browsers history. First of all, window part
can be removed from window.history just using history object alone works fine.
The JS history object contains an array of URLs visited by the user. By using
history object, you can load previous, forward or any particular page using
various methods.
.
Methods
of JavaScript history object :
•forward():
It loads the next page. Provides a same effect as clicking back in the browser.
•back():
It loads the previous page. Provides a same effect as clicking forward in the
browser.
•go():
It loads the given page number in browser. history.go(distance) function
provides a same effect as pressing the back or forward button in your browser
and specifying the page exactly which you want to load.
Example
1
<html>
<head>
</head>
<body>
<b>Press
the back button</b>
<input
type="button" value="Back"
onclick="previousPage()">
<script>
function
previousPage()
{
window.history.back();
}
</script>
</body>
</html>
Example
2
<html>
<body>
<b>Press
the forward button</b>
<input
type="button" value="Forward"
onclick="NextPage()">
<script>
function
NextPage()
{
window.history.forward()
}
</script>
</body>
</html>
Example
3
<html>
<head>
</head>
<body>
<input
type="button" value="go" onclick="NextPage()">
<script>
function
NextPage()
{
window.history.go(4);
}
</script>
</body>
</html>
Location Object
The
location object contains information about the current URL.
The
location object is part of the window object and is accessed through the
window.location property.
Location
Object Properties
hash:-Sets
or returns the anchor part (#) of a URL
host:-Sets
or returns the hostname and port number of a URL
hostname:-Sets
or returns the hostname of a URL
href:-Sets
or returns the entire URL
pathname:-Sets
or returns the path name of a URL
port:-Sets
or returns the port number of a URL
protocol:-Sets
or returns the protocol of a URL
Location
Object Methods
assign():-Loads
a new document
reload():-Reloads
the current document
replace():-Replaces
the current document with a new one
<html>
<body>
<button
onclick="myFunction()">Replace document</button>
<script>
function
myFunction()
{
location.replace("https://www.foresight.com")
}
</script>
</body>
</html>
javaScript Math
The
JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
JavaScript
Math Methods
max():-It
returns maximum value of the given numbers.
min():-It
returns minimum value of the given numbers.
pow():-It
returns value of base to the power of exponent.
sqrt():-It
returns the square root of the given number
abs():-It
returns the absolute value of the given number.
JavaScript
Math max() method
The
JavaScript math max() method compares the given numbers and returns the maximum
value.
<html>
<body>
<script>
document.writeln(Math.max(22,34,12,15)+"<br>");
document.writeln(Math.max(-10,-24,-12,-20));
</script>
</body>
</html>
JavaScript
Math min() method
The
JavaScript math min() method compares the given numbers and returns the minimum
value.
<html>
<body>
<script>
document.writeln(Math.min(22,34,12,15)+"<br>");
document.writeln(Math.min(-10,-24,-12,-20));
</script>
</body>
</html>
JavaScript
Math pow() method
The
JavaScript math pow() method returns the base to the exponent power such as
baseexponent. In other words, the base value (x) is multiplied with itself
exponent times (y).
<html>
<body>
<script>
document.writeln(Math.pow(2,3)+"<br>");
document.writeln(Math.pow(5,1.4));
</script>
</body>
</html>
JavaScript
Math sqrt() method
The
JavaScript math sqrt() method returns the square root of a number. If the
provided number is negative, it returns NaN.
<html>
<body>
<script>
document.writeln(Math.sqrt(16)+
"<br>");
document.writeln(Math.sqrt(12));
</script>
</body>
</html>
JavaScript
Math abs() method
The
JavaScript math abs() method returns an absolute value of a given number. The
abs() is a static method of Math.
<html>
<body>
<script>
document.writeln(Math.abs(-4)+"<br>");
document.writeln(Math.abs(-7.8)+"<br>");
document.writeln(Math.abs('-4'));
</script>
</body>
</html>
JavaScript Date
Object
The
JavaScript date object can be used to get year, month and day. You can display
a timer on the webpage by the help of JavaScript date object.
You
can use different Date constructors to create date object. It provides methods
to get and set day, month, year, hour, minute and seconds.
Constructor
You
can use 4 variant of Date constructor to create date object.
1.Date()
2.Date(milliseconds)
3.Date(dateString)
4.Date(year,
month, day, hours, minutes, seconds, milliseconds)
JavaScript
Date Methods
getDate():-It
returns the integer value between 1 and 31 that represents the day for the
specified date on the basis of local time
getDay():-It
returns the integer value between 0 and 6 that represents the day of the week
on the basis of local time.
getHours():-It
returns the integer value between 0 and 23 that represents the hours on the
basis of local time.
getMilliseconds():-It
returns the integer value between 0 and 999 that represents the milliseconds on
the basis of local time.
getMinutes():-It
returns the integer value between 0 and 59 that represents the minutes on the
basis of local time.
getSeconds():-It
returns the integer value between 0 and 60 that represents the seconds on the
basis of local time.
setDate():-It
sets the day value for the specified date on the basis of local time.
setDay():-It
sets the particular day of the week on the basis of local time.
setFullYears():-It
sets the year value for the specified date on the basis of local time.
setHours():-It
sets the hour value for the specified date on the basis of local time.
Example:-1
<html>
<body>
Current
Date and Time: <span id="txt"></span>
<script>
var
today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
</body>
</html>
Example:-2
<html>
<body>
<script>
var
date=new Date();
var
day=date.getDate();
var
month=date.getMonth()+1;
var
year=date.getFullYear();
document.write("<br>Date
is: "+day+"/"+month+"/"+year);
</script>
</body>
</html>
Example:-3
<html>
<body>
Current
Time: <span id="txt"></span>
<script>
var
today=new Date();
var
h=today.getHours();
var
m=today.getMinutes();
var
s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</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
1.
By string literal
2.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:
<html>
<body>
<script>
var
str="This is string literal";
document.write(str);
</script>
</body>
</html>
2)
By string object (using new keyword)
<html>
<body>
<script>
var
stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>
JavaScript
String Methods
charAt():-It
provides the char value present at the specified index.
<html>
<body>
<script>
var
str="JavaPROGRAMME";
document.writeln(str.charAt(4));
</script>
</body>
</html>
Ans:-P
concat():-It
provides a combination of two or more strings.
<html>
<body>
<script>
var
x="FORESIGHT";
var
y=".com";
document.writeln(x.concat(y));
</script>
</body>
</html>
toLowerCase()
Method
The
JavaScript string toLowerCase() method is used to convert the string into
lowercase letter. This method doesn't make any change in the original string.
<html>
<body>
<script>
var
str = "JAVAPROGRAMME";
document.writeln(str.toLowerCase());
</script>
</body>
</html>
toLocaleLowerCase():-It
converts the given string into lowercase letter on the basis of host?s current
locale.
<html>
<body>
<script>
var
str="JAVA";
document.writeln(str.toLocaleLowerCase());
</script>
</body>
</html>
toUpperCase()
Method
The
JavaScript string toUpperCase() method is used to convert the string into
uppercase letter. This method doesn't make any change in the original string.
<html>
<body>
<script>
var
str = "java";
document.writeln(str.toUpperCase());
</script>
</body>
</html>
toLocaleUpperCase()
Method
JavaScript
string toLocaleUpperCase() method converts the string to uppercase letter on
the basis of host's current locale. In most cases, this method returns the
similar result as the toUpperCase() method.
<html>
<body>
<script>
var
str="java";
document.writeln(str.toLocaleUpperCase());
</script>
</body>
</html>
JavaScript Array
Indexed
Array:-These arrays are indexed numerically. The first element of an indexed
array is considered to be at position zero. The Second element of an indexed
array is considered to be at position one. Range is 0-9.
Example:-
Apple[0]=”red”;
Apple[1]=”blue”;
Apple[2]=”green”;
Associative
Array:-These arrays are indexed using names as keys.
Apple[a]=”red”;
Apple[b]=”blue”;
Apple[c]=”green”;
<html>
<body>
<script>
var
apple=new array(“a”,”b”,”c”,”d”,”e”,”f”,”g”);
document.write(“Reverse”+apple.reverse());
document.write(“Join”+apple.join(“;”));
document.write(“pop”+apple.pop());
document.write(“Shift”+apple.shift());
</script>
</body>
</html>
Ans:-
reverse :-g,f,e,c,b.a
Join
:- g;e;c;b;a
Pop
:-a
Shift:-
g
JavaScript
array is an object that represents a collection of similar type of elements.
There
are 3 ways to construct array in JavaScript
1.
By array literal
2.By
creating instance of Array directly (using new keyword)
3.
By using an Array constructor (using new keyword)
JavaScript
Array Methods
concat()
Method
The
JavaScript array concat() method combines two or more arrays and returns a new
string. This method doesn't make any change in the original array.
concat():-It
returns a new array object that contains two or more merged arrays.
<html>
<body>
<script>
var
arr1=["C","C++","Python"];
var
arr2=["Java","JavaScript","Android"];
var
result=arr1.concat(arr2);
document.writeln(result);
</script>
</body>
</html>
->C,C++,Python,Java,JavaScript,Android
pop()
method
The
JavaScript array pop() method removes the last element from the given array and
return that element. This method changes the length of the original array.
<html>
<body>
<script>
var
arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal
array: "+arr+"<br>");
document.writeln("Extracted
element: "+arr.pop()+"<br>");
document.writeln("Remaining
elements: "+ arr);
</script>
</body>
</html>
Orginal
array: AngularJS,Node.js,JQuery
Extracted
element: JQuery
Remaining
elements: AngularJS,Node.js
push()
method
The
JavaScript array push() method adds one or more elements to the end of the
given array. This method changes the length of the original array.
<html>
<body>
<script>
var
arr=["AngularJS","Node.js"];
arr.push("JQuery");
document.writeln(arr);
</script>
</body>
</html>
->AngularJS,Node.js,Jquery
reverse()
method
The
JavaScript array reverse() method changes the sequence of elements of the given
array and returns the reverse sequence. In other words, the arrays last element
becomes first and the first element becomes the last. This method also made the
changes in the original array.
<html>
<body>
<script>
var
arr=["AngulaJS","Node.js","JQuery"];
var
rev=arr.reverse();
document.writeln(rev);
</script>
</body>
</html>
->JQuery,Node.js,AngulaJS
sort()
method
The
JavaScript array sort() method is used to arrange the array elements in some
order. By default, sort() method follows the ascending order.
<html>
<body>
<script>
var
arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var
result=arr.sort();
document.writeln(result);
</script>
</body>
</html>
->AngularJS,Bootstrap,JQuery,Node.js
JavaScript Number Object
The JavaScript number object enables you to represent
a numeric value. It may be integer or floating-point. JavaScript number object
follows IEEE standard to represent the floating-point numbers.
<html>
<body>
<script>
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
document.write(x+" "+y+"
"+z+" "+n);
</script>
</body>
</html>
Ans:- 102 102.7 130000 16
isInteger() method
The JavaScript number isInteger() method
determines whether the given value is an integer. It returns true if the value
is an integer, otherwise it returns false.
<html>
<body>
<script>
var x=0;
var y=1;
var z=-1;
document.writeln(Number.isInteger(x));
document.writeln(Number.isInteger(y));
document.writeln(Number.isInteger(z));
</script>
</body>
</html>
Ans:- true true true
parseFloat() method
The JavaScript number parseFloat() method parses a
string argument and converts it into a floating point number. It returns NaN,
if the first character of given value cannot be converted to a number.
<html>
<body>
<script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseFloat(a)+"<br>");
document.writeln(Number.parseFloat(b)+"<br>");
document.writeln(Number.parseFloat(c)+"<br>");
document.writeln(Number.parseFloat(d)+"<br>");
document.writeln(Number.parseFloat(e));
</script>
</body>
</html>
Ans:-
50
50.25
NaN
50
50.25
parseInt() method
The JavaScript number parseInt() method parses a
string argument and converts it into an integer value. With string argument, we
can also provide radix argument to specify the type of numeral system to be
used.
<html>
<body>
<script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.writeln(Number.parseInt(a)+"<br>");
document.writeln(Number.parseInt(b)+"<br>");
document.writeln(Number.parseInt(c)+"<br>");
document.writeln(Number.parseInt(d)+"<br>");
document.writeln(Number.parseInt(e));
</script>
</body>
</html>
Ans:-
50
50
NaN
50
50
Event Handling
An HTML event can be something the browser does, or
something a user does.
Here are some examples of HTML events:
•An HTML web page has finished loading
•An HTML input field was changed
•An HTML button was clicked
Often, when events happen, you may want to do
something.
Common HTML Events
onchange:-An HTML element has been changed
onclick :-The user clicks an HTML element
onmouseover:-The user moves the mouse over an HTML
element
onmouseout:-The user moves the mouse away from an HTML
element
onkeydown:-The user pushes a keyboard key
onload:-The browser has finished loading the page
Example
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
<form>
<input type = "button" onclick =
"sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Example
<html>
<head>
<script type = "text/javascript">
<!--
function over()
{
document.write ("Mouse Over");
}
function out()
{
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover = "over()" onmouseout =
"out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>