Introduction to JavaScript
Introduction to JavaScript
Introduction to JavaScript
specifically for use in web browsers to make websites more dynamic and
attractive.
execution.
Why JavaScript?
3) Control Browsers
5) Create cookies
page.
6) Add interactivity to the website
button.
Features of JavaScript
a) A great programming tool for HTML
d) Saves Time
e) DOM
objects.
g) Interpreted Language
It can be used or executed with ease without pre-
compilation.
Advantages
v. GUI features
a) Client-side JavaScript does not allow the reading or writing of files. This
support available.
Java Vs JavaScript
JavaScript Java
language.
standalone applications.
compiler.
a browser. We can alter it, original text and alter it, but
1. We type the URL in the browser. The browser sends the http
2. Server checks the request and returns the HTML page to the
browser.
3. The Browser gets the HTML page and displays the content. The
4. Assume that user gets Feedback form. The user will type the values
in the text box and submits the form. We need to validate the form.
server.
JavaScript syntax
webpage.
<head> tags.
Syntax:
<script type=”text\javascript”>
JavaScript code
</script>
tags)
<html>
<head>
<script type=”text\javascript”>
The script tag has been placed inside the head section.
</script>
</head>
</html>
section.
In the Body Section
<html>
<body>
<script type=”text\javascript”>
body section.”);
</script>
</body>
</html>
In an External File
rewrite.
script.
JavaScript Comments
Single-line comments: //
/*
*This is a multi
*line comment
*/
/*
Multiline comment
*/
JavaScript Variables
Declaring Variables
With variables, we can store information in one part of the program and
var age;
Note:
consists of more than one word, separate each word with an underscore.
Ex1: age=100;
sum=x=y=0;
</script>
var sum, x, y;
sum=x=y=0;
</script>
age =55;
Ex2: age=55;
name =”Snigda”;
age =55;
document.write(name+”is”+age);
</script>
scope.
Local Scope
Global Scope
Functions
Ex:
document.write(message+”<br/>”);
DisplayMessage(“Hello”);
DisplayMessage(“Mr.John”);
</script>
Ex:
function isEven(num)
if(num%2==0)
return num;
We can also define our own sorting function using call back
functions.
This call back function must have two input arguments and always
returns -1, 0 or 1.
If call back func (a,b) is less than 0, place a before b.
If call back func(a,b) returns 0, leave a and b unchanged in respect
to eachother.
If call back func(a,b) is greater than 0, place a after b.
Ex: var MyArray= new Array( );
myArray= [20, 10, 40, 50, 30];
function callbackFunc(a,b)
{
return a-b;
}
myArray.sort(callbackFunc);
Validation API
Property Description
a. Validity Contains Boolean properties related to the
validity of an input element.
b. ValidationMessage Contains the message a browser will display
when the validity is false.
c. willValidate Indicates if an input element will be validated.
Validity Properties
Property Description
a) customError Set to true, if a custom validity message
is set.
b) patternMismatch Set to true, if an elements value does not
match its pattern attribute.
c) rangeOverflow Set to true, if an elements value is greater
than its max attribute.
d) rangeUnderflow Set to true, if an elements value is less
than its min attribute.
e) stepMismatch Set to true, if an elements value is invalid
per its step attribute.
f) tooLong Set to true, if an elements value exceeds
its maxLength attribute.
g) typeMismatch Set to true, if an elements value is invalid
per its type attribute.
h) valueMissing Set to true, if an element( with a required
attribute) has no value.
i) Valid Set to true, if an elements value is valid.
Examples
If the number in an input field is greater than 100, display a message.
The rangeOverflow Property
<p id=”demo”></p>
<script>
function myFunction( )
if(document.getElementById(“id1”).Validity.rangeOverflow)
document.getElementById(“demo”).innerHTML= txt;
}
</script>
Example: If the number in an input field is less than 100, display a message:
<script>
function myFunction( )
if(document.getElementById(“id1”).Validity.rangeUnderflow)
document.getElementById(“demo”).innerHTML= txt;
}
</script>
Levels of DOM
1) DOM 0
All browsers have a DOM which gives you access to various parts
of the document.
The level 0 DOM is the oldest of them.
It was implemented in NetScape2 and 3 and still works in all
JavaScript browsers.
It gives easy access to forms and their elements, images and links.
2) DOM 1
The initial DOM standard known as “DOM level 1”, was
recommended by W3C in 1998.
DOM level 1 provided a complete model for an entire HTML or
XML document, which included means to change any portion of
the document.
3) DOM 2
Level 2 is complete and many of the properties, methods and
events have been implemented by today’s browsers.
It has sections that add specifications for events and stylesheets.
4) DOM 3
Level 3 achieved recommendation status in 2004.
It is intended to resolve lot of complications that still exist in the
event model in level-2 of the standard.
This adds support for XML features, such as content models.
Only a few browsers support some features of level 3.
document
<html>
<head> <body>
<title>
<tr>
<tr>
<td
DOM Objects
1) Window Location
The window.location object can be used to get the current page
address (URL) and to redirect the browser to a new page.
The window.location.href property returns the URL of the current
page.
Ex:
document.getElementById(“demo”).innerHTML=
“page Location is”+window.location.href;
Window Location Hostname
The window,location.hostname property returns the name of the
internet host (of the current page).
Ex:
Document.getElementById(“demo”).innerHTML=”pagehostna
me is”+window.location.hostname;
2) Window History
The window.history object contains the browser history,
To protect the privacy of the users, there are limitations to how
JavaScript can access this object.
history.back( )- same as clicking back in the browser.
history.forward( )- same as clicking forward in the browser.
The history forward( ) method loads the next URL in the history
list.
Ex: Create a forward button on a page
<html>
<head>
<script>
function goForward( )
{
window.history.forward( );
}
</script>
</head>
<body>
<input type=”button” value=“Forward”
onclick=”goForward( )”>
</body>
</html>
3) Window Navigator
The window.navigator object contains information about the
visitor’s browser.
Ex:
navigator.appName
navigator.appCodeName
navigator.platform
Client-Side JavaScript
JavaScript - Objects
Object Properties
Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used
throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
Ex: var str = document.title;
Object Methods
Methods are the functions that let the object do something or let
something be done to it.
There is a small difference between a function and a method.
Function is a standalone unit of statements and a method is attached to
an object and can be referenced by this keyword.
Methods are useful for everything from displaying the contents of the
object to the screen to performing complex mathematical operations on a
group of local properties and parameters.
document.write("This is test");
User-Defined Objects
Arrays
Array Methods
Array methods are used to manipulate arrays such as adding a new
element at the beginning or end of an array, removing an element
from the end of an array, reversing an array and so on.
JavaScript provides a set of methods for doing all of these.
a) concat( )-concatenates elements from one array to
another array.
b) join( )- Joins the elements of an array by a separator to
form a string.
c) pop( )-Removes and returns the last elements of an array.
d) push( )-Adds elements to the end of an array.
e) reverse( )- Reverses the order of elements in an array.
f) shift( )-Removes and returns the first element of an array.
g) slice( )-Creates a new array from elements of an existing
array.
h) sort( )-Sorts an array alphabetically or numerically.
i) splice( )-Removes and/or replaces elements of an array.
j) toLocaleString( )- Returns a string representation of the
array in local format.
k) toString( )- Returns a string representation of the array.
l) unshift( )- Adds elements to the beginning of an array.
bestPlaces[0]= “Agra”;
bestPlaces[1]= “London”;
bestPlaces[2]= “Bangalore”;
(OR)
bestPlaces.shift(“Agra”,”Bangalore”);
Boolean
Syntax
var val = new Boolean(value);
Boolean Properties
Sl NO Property Description
Boolean Methods
Sl NO Method Description
Syntax
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
.
Here is a description of the parameters −
No Argument − With no arguments, the Date() constructor creates a
Date object set to the current date and time.
Date Properties
Sl NO Property Description
Date Methods
Sl NO Method Description
Function object
Sl NO Property Description
Sl NO Method Description
Math Object
The math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math as an
object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function
as Math.sin(x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
Sl NO Property Description
Math Methods
Sl NO Method Description
Number Object
Number Properties
Here is a list of each property and their description.
Sl NO Property Description
Number Methods
The Number object contains only the default methods that are a part of every
object's definition.
Sl NO Method Description
Sl NO Method Description
JavaScript Operators
var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
String Properties:
Property Description
1. Constructor Returns a reference to the string
function that created the object.
2. Length Returns the length of the string.
3. Prototype The prototype property allows you to
add properties and method to an
object.
String Methods:
Method Description
1. charAt( ) Returns the character at the specified
index.
Ex: var b=’I am a JavaScript
Learner.’
document.write(b.charAt(7));
o/p: ‘a’
2. indexOf( ) Returns the index within the calling
string object of the first occurrence of
the specified value, or -1 if not found.
Ex: var a=’Hello World!’;
document.write(a.indexOf(‘l’));
o/p: 2.
If the same character occurs more
than once, this method gives the first
occurrence.
3. lastIndexOf( ) Returns the index within the calling
string object of the last occurrence of
the specified value, or -1 if not found.
Ex: var b =’I am a JavaScript
Learner’;
document.write(b.lastIndexOf(‘a’));
o/p: 20
because that’s the index of the last ‘a’
in the string.
4. search( ) Executes the search for a match
between a regular expression and a
specified string.
Ex: var str,result;
str=”JavaScript”;
result=str.search(“script”);
document.write(“Substring found at
position:”+result);
o/p:Substring found at position :4
5. substr( ) Returns the characters in a string
beginning at a specified location
through the specific number of
characters.
Ex: var a=”Hello World!”;
document.write(a.substr(4,8));
starts at the characters with index
4(‘o’) and then gives 8 characters, so
the output is 0 world!
6. substring() Returns the characters in a string
between two indexes into the string.
Ex: var a=’Hello World!’;
document.write(a.substring(4,8));
gives ‘o wo’, from the first ‘o’(index
4) to the second one (index 7).
7. toLowerCase( ) Returns the calling string value
converted to Lowercase.
Ex: var b=’Srikanth’;
document.write(b.toLowerCase( ));
o/p: ‘srikanth’
2. window.alert( )
The alert( ) method is part of window object.
The alert( ) method shows the message in a small message
box.
The message box contains the string and an “ok” button on
it.
If the user presses the “ok” button the message box
disappears.
The message to be displayed has to be passed as parameter
to the alert( ) method.
The window’s alert( ) method is used to send a warning to
the user or alert him or her to do something.
Ex: <html>
<head>
<title>Alert Demo</title>
<script type=”text\javascript”>
window.alert(“your email id is incorrect.”)
</script>
</head>
</html>
3. window.status
The status is not a method and it is property of window
object.
The window.status property show the message in status bar.
The message to be displayed has to be assigned to the
window.status property.
Ex: <html>
<head>
<title> Status Demo</title>
<script type=”text\javascript”>
window.status=“It is my own webpage.”;
</script>
</head>
</html>
4. window.prompt( )
A prompt( ) method asks the user for some small amount of
information such as password, completion of a form input,
or personal information.
The prompt dialog box pops up with a simple textfield box.
After the user enters text into the prompt dialog box, its
value is returned.
This method takes two arguments: a string of text that is
displayed as a question to the user, prompting the user to do
something and another string of text that is the initial default
setting for the box.
If this argument is an empty string, nothing is displayed in
the box.
The prompt( ) method always returns a value.
If the user clicks the OK button all the text in the box is
returned.
Ex: <html>
<head>
<title> Prompt Demo</title>
<script type=”text\javascript”>
5. window.confirm( )
The confirm box is used to answer a user’s answer to a
question.
The user must agree before order or delete a file where a yes
or no confirmation determines what will happen next.
Question mark will appear in the box with an OK button and
a Cancel button.
If the user clicks the OK button, true is returned, if he clicks
the cancel button, false is returned.
This method takes only one argument, the question that we
are going to ask the user.
Ex:
<html>
<head>
<title> Confirm Demo</title>
<script type=”text\javascript”>
Brackets
The string object provides four methods that work with regular
expressions. They are:
a) The match( ) method
The match( ) method is used to search for a pattern of characters
in a string.
It returns an array where each element of the array contains
each matched pattern that was found.
If no match is found, returns NULL.
With the g flag , match( ) searches globally through the string
for all matching substrings.
Ex:
<script type= “text\javascript”>
var matchArray= new Array( );
var string= “I love the smell of clover”;
var regex= /love/g;
matchArray= string.match(regex);
</script>
Each time the pattern \love\ is found in the string, it will be
assigned as a new element of the array called matchArray.
If the g modifier is removed, only the first occurrence of the
match will be returned, and only one element will be assigned to
the array matchArray.
</script>
<form name=”secondForm”>
document.forms[1].elements[0] Input type=”text” name=”CourseText”/>
document.forms[1].elements[1] Input type=”text” name=”SemText”/>
document.forms[1].elements[2] Input type=”text” name=”PercentageText”/>
document.forms[1].elements[3] Input type=”submit” name=”myButton2”/>
</form>
</body>
In the above code, we have used 3 text boxes and one submit button in
each form.
We can get the values entered in each textbox using value property in
JavaScript code
<script type=”text/javascript>
function function1( )
{
var Name= document.forms[0].elements[0].value;
var Age= document.forms[0].elements[1].value;
var Phone= document.forms[0].elements[2].value;
}
</script>
Disadvantage
Syntax
document.formname.elementname;
document.firstForm.NameText
document.firstForm.AgeText
document.firstForm.PhoneText
document.firstForm.myButton1
Advantages
Using names, we can put all elements somewhere else in the
page and still have a working script, while a script using
numbers will have to be changed.
We can get the value of any textbox using the below code:
var user_input= document.firstForm.NameText.value;
If we would like to add text to textbox dynamically, we can
do this using
document.firstForm.NameText.value=”The new value”;
3. Accessing form elements using getElementById( ) method
The getElementById( ) method takes the id of HTML
element as its argument and returns a reference to that
element.
The getElementById( ) is a method of the document object
and must be written as document.getElementById( ).
With the reference we can manipulate the element in
JavaScript code.
Suppose, we have a paragraph tag defined with an id
attribute, as
<p id=”para1”>This is the paragraph.</p>
We can get a reference to the p element with the
getElementById( ) method as follows
var p_element=document.getElementById(“para1”);
The p_element is a reference to the p element identified as
“para 1” and can be used with the DOM properties.
alert(p_element.nodeName);
alert(p_element.childNodes[0].nodeValue);
Ex:
<form name=”firstForm”>
<input type=”text” id=”NameText/>
<input type=”text” id=”AgeText/>
<input type=”text” id=”PhoneText/>
<input type=”submit” id=”myButton1/>
</form>
The elements can be accessed using the below code:
var name_element=document.getElementById(“NameText”);
var age_element=document.getElementById(“AgeText”);
var phone_element=document.getElementById(“PhoneText”);
var submit_element=document.getElementById(“myButton”);
We can print the values entered in the textboxex using the code
below:
alert(document.getElementById(“NameText”).value;
alert(document.getElementById(“AgeText”).value;
alert(document.getElementById(“PhoneText”).value;
One of the way is assigning the event handler script to an event tag
attribute.
Ex:
<a href=”books.html” onclick=”alert(“I have clicked book
page!”)”>
alert(“I have clicked book page!”) is executed whenever the click
event takes place on this link. It is registered as an event handler.
If we want more than one statement to be executed when an event
occurs, we can create user defined function.
Ex:
<input type=”click” onclick=”myFunction( )”>
The function myFunction( ) is executed whenever the button is
submitted in the form.
b) Mouse Events
JavaScript Programs have the ability to track mouse movement and
button clicks as they relate to the webpage and control.
c) Key events
They are more commonly found in windows applications than in
web-based programming.
3 main key events in HTML
The keydown event occurs when almost any keyboard key has
been pressed down, including non-alphanumeric key such as
HOME, ESCAPE, INSERT and DELETE.
The keypress event, only fires when certain alphanumeric keys are
pressed, including punctuation, SPACEBAR and ENTER.
The keyup event is the complement of keydown, fires when
almost any key has been released.
d) HTML events
HTML events do not belong to UI, mouse or key event categories.
HTML events are triggered directly by a user action.
Event Event Handler Fires When Applicable
Name Name/Tag Attribute
Load onload Browser finishes <body>
loading
document.
Unload onunload Browser about to <body>
unload document
submit onsubmit Form about to be <form>
submitted
Reset onreset Form about to be <form>
reset
Select onselect Textbox contents <input>,<textarea>
selected
Change onchange Form control <input>,<textarea>,<select>
contents changed
i. Load event
The onload event handler is called when the HTML document
finishes loading into browser window.
This event is used for initialization.
v. Select event
The select event occurs when the user selects text inside a
textbox or text area.
The load and unload events are the most frequently used events
in the body tag.
The onload event handler is invoked on the occurrence of a load
event, i.e., when a document is completely finished loading.
The onUnload event handler is invoked when the page is exited
or reset.
Ex:
<html>
<head>
<title>onload Event</title>
<script type=”text/javascript”>
function welcome( )
{
alert(“Welcome to our website”);
}
</script>
</head>
<body onload=”welcome( );”>
<p> This paragraph will be displayed first and then load
event will be fired</p>
</body>
</html>