Javascript
Javascript
Client-side scripting:
Run in the client browser and process requests without call backs to the server
client-side scripting (JavaScript) benefits
usability: can modify a page without having to post back to the server (faster UI)
efficiency: can make small, quick changes to page without waiting for server
event-driven: can respond to user actions like clicks and key presses
Server-side scripting:
server-side programming (PHP,servlets,JSP,..) benefits:
security: has access to server's private data; client can't see source code
compatibility: not subject to browser compatibility issues
power: can write files, open connections to servers, connect to databases, ...
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
Works in the back end which could not be visible at the Works at the front end and script are visible among the
client end. users.
Processing Requires server interaction. Does not need interaction with the server.
Could effectively customize the web pages and provide Can reduce the load to the server.
dynamic websites.
Applications of JavaScript
Client side validation
Manipulating HTML Pages
User notifications
Back-end data loading
Presentations
There are two ways to insert JavaScript code into an HTML code
1) Internal JavaScript:
JavaScript code can be inserted either in head or body section of HTML using <script> tag.
<script type=“text/JavaScript” language=“JavaScript”>
Java Script Code
</script>
2) External JavaScript:
We can create external JavaScript file with .js extension and embed it in many html pages.
<script type=“text/JavaScript” language=“JavaScript” src=”js file path”>
Java Script Code
</script>
message.js
The keyword var specifies that the variable is a local variable and is visible within the scope in which it
is declared.
Examples: var sum=0; //number
var msg=“hello world”; //string
var found=false; //boolean
Example:
2) Global variables
<!DOCTYPE html>
A global variables is created without the keyword <html>
var. <body>
It is created by assigning a value to it. <h2>JavaScript Variables</h2>
Syntax: variable=value; <p>In this example, x, y, and z are variables.</p>
Examples: x=1; <script type=“text/JavaScript”>
lang=“JavaScript”; var x = 10;
flag= true; var y = 20;
These variables are created as soon as the block is var z=x+y;
executed and become visible from that instant. document.write(z);
</script>
</body>
</html>
Undefined variables:
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this
statement:
Example: var carName;
Prompt box.
Alert Box:
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
window.alert("sometext");
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true.
If the user clicks "Cancel", the box returns false.
window.confirm("sometext");
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
The user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value.
If the user clicks "Cancel" the box returns null.
window.prompt("sometext","defaultText");
Functions
A JavaScript function is a block of code designed to perform a particular task.
A function is a set of statements that performs some tasks or does some computation and then returns the
result to the user.
A JavaScript function is executed when "something" invokes it (calls it).
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
function name(parameter1, parameter2, parameter3)
{
// code to be executed
}
The code inside the function will execute when "something" invokes (calls) the function:
--When an event occurs (ex: when a user clicks a button)
--When it is invoked (called) from JavaScript code
--Automatically (self invoked).
• A function must be declared before it is called, this is applicable for variables also.
-It means javascript functions and declare global variables within the head section.
-Other javascript statements, including function calls, can be placed anywhere within the body tag.
Example:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
Example:
<html>
<head>
<script type=“text/JavaScript”>
function func1()
{
document.write("This is simple function");
}
</script>
</head>
<body>
<h3>Functions</h3>
<input type="button" onclick="func1()" value="click">
</body>
</html>
Note: The onclick event occurs when the user clicks on an element.
Example: Example:
<html> <html>
<head>Javascript</head> <head>Javascript</head>
<body> <body>
<h3>Passing parameters</h3> <h3>Functions</h3>
<script> <script>
function mul( a , b){ var x = myFunction(4, 6);
return a*b;
} function myFunction(a, b)
document.write(mul(12,13)); { return a * b;
</script> }
</body> document.write(x);
</html> </script>
</body>
</html>
Program 2:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<!DOCTYPE html>
<html>
<head></head>
<body>
<h4>Simple Arrays</h4>
<script type="text/JavaScript">
var fruits=["orange","mango","apple"];
for (i=0;i<fruits.length;i++)
{
document.write(fruits[i] + "<br/>");
}
</script>
</body>
</html>
Using the JavaScript Keyword new/Using constructor
new keyword is used to create instance of array.
There is no need to use the JavaScript's built-in array constructor new Array().
var points = new Array(); // Bad
var points = []; // Good
The following example also creates an Array, and assigns values to it:
var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some unexpected results.
Example: var fruits=new Array();
fruits[0]=“apple”;
fruits[1]=“orange”;
fruits[2]=“mango”;
Array methods
1)concat( )-It returns a new array object that contains two or more merged arrays.
var res=array.concat(arr1,arr2,....,arrn) ;
2)indexOf( )-It searches the specified element in the given array and returns the index of the first match.
var n=array.indexOf(element,index) ;
3)join( )-It joins the elements of an array as a string.
var res=array.join(separator) ;// default separator is ,
4)lastIndexOf( )-It searches the specified element in the given array and returns the index of the last
match.
var n=array.lastIndexOf(element,index);
Example Program:
<html>
var arr4=["C","C++","Python","C+
<body> +","Java"];
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result= arr4.lastIndexOf("C+
+");
var result=arr1.concat(arr2); document.writeln("last index
document.writeln("concatination:”+result+"<br>");
of c++: "+result+"<br>");
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
</script>
document.writeln("index of C++: "+result+"<br>");
</body>
var arr3=["PhP","Servlets","JSP"] </html>
var result=arr3.join(" ")
document.write("joins the elements as a string:
"+result+"<br>");
9) unshift()-It adds one or more elements in the
5) pop( )-It removes and returns the last element of an
beginning of the given array.
array.
array. unshift(e1,e2,....,en);
var x=array.pop() ;
Example-
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Output: Banana,Orange,Lemon,Kiwi
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruit
Output: Orange,Apple,Mango
Program: var result=arr.slice(0,2);
document.writeln("slice: "+result+"<br>");
<html>
<body> var arr=[2,4,1,8,5];
<script> var result=arr.sort(); //1,2,4,5,8
var arr=["AngularJS","Node.js","JQuery"]; document.writeln("sorted array:
document.writeln("Orginal array: "+arr+"<br>");
"+result+"<br>");
document.writeln("Extracted element: "+arr.pop() document.writeln("element at first
+"<br>"); place:"+result[0]+"<br>");
document.writeln("Remaining elements: "+ arr+"<br>");
arr.push("PhP");
var
document.writeln("Remaining elements: "+ arr+"<br>"); arr=["Monday","Tuesday","Thursday","Fri
day"];
var rev=arr.reverse(); var result=arr.splice(2,0,"Wednesday")
document.writeln("reverse of arr is: "+rev+"<br>"); document.writeln(arr);
var result=arr.shift();
document.writeln(result+"<br>"); </script>
</body>
var result=arr.unshift("J2EE");
</html>
document.writeln(arr+"<br>");
Strings
String is an object that represents a sequence of characters
2 ways to create string in JavaScript
var stringname="string value";
var stringname=new String("string literal");
String Methods 5) lastIndexOf( )-It provides the position of a char value
present in the given string by searching a character
1) charAt( )-It provides the char value present at the
from the last position.
specified index.
var n=lastIndexOf(ch[,position]);
var c=String.charAt(index);
var n=lastIndexOf(str[,position]);
4) indexOf( )-It provides the position of a char value 8) search( )- It searches a specified regular
present in the given string. expression in a given string and returns its
var n=indexOf(ch[,position]) position if a match occurs.
var n=indexOf(str[,position]) string.search(regexp);
9) match( )-It searches a specified regular expression in a 13) toString()-It provides a string
given string and returns that regular expression if a representing the particular object.
match occurs. object.toString();
string.match(regexp);
var str="JavaScript";
document.writeln("char value present at index-"+str.charAt()+"<br>");//print first character
document.writeln("unicode value of character "+str.charCodeAt(3)+"<br>");
var str4="JavaScript";
document.writeln("substring "+str4.substr(1,4)+"<br>");
Once an object is created its properties are accessed using dot(.) operator
Obj_name.propertyName;
Ex: p.x or p.y
Examples: Circle={x:2,y:3,r:10};
aCircle2={center:{x:2,y:3},r:10};
stud={name:”xyz”,id:501,marks:{85,90,89,88}};
Javascript object by using instance of object/object constructor:
In Javascript ,we can create empty objects by using Object constructor and new operator
Here, you need to create function with arguments. Each argument value can be assigned in the current object by
using this keyword.
In JavaScript a class is defined by a function , which acts as the constructor for the class.
Objects are created with the help of this constructor function and new operator.
Ex: The following is the class definition for the class Point
function Point(){
}
p= new Point(); or p=new Point;
p.x=20;
p.y=30;
Parameterized constructor is used to add some Properties may be added per-object basis
common properties and set their values. Obj_name.new_prop_name=value;
Other properties may be added latter on a per-object Ex: p1.color=“red”;
basis as well as per-class basis, as and when needed.
The this keyword refers to the current Properties may be added per-class basis
object.
class_name.prototype.new_prop_name=value;
function Point(x,y)
Ex: p1.prototype.color=”green”;
{
this.x=x;
this.y=y;
}
Cretae objects:
p1=new Point(10,20);
P2=new Point(100,200);
Example: Example:
<html>
<html> <body>
<script>
<body>
function emp(id,name,salary){
<script> this.id=id;
emp={id:102,name:“Rani",salary:40000} this.name=name;
this.salary=salary;
document.write(emp.id+" "+emp.name+"
}
"+emp.salary); e=new emp(103,"Kavitha",30000);
</script>
document.write(e.id+" "+e.name+" "+e.salary);
</body>
</script>
</html> </body>
</html>
Output: Output:
102 Rani 40000 103 Kavitha 30000
Adding New methods:
It is a two step process:
Define the Function
Associate it within the constructor during object creation or make this association later.
Ex:
function carea()
{
return 3.14159*this.r*this.r;
}
function Circle(x,y,r){
this.x=x;
this.y=y;
this.r=r;
this.area=carea;
}
//Once the function carea is associated with the property area,it may be called as follows:
var c=new Circle(1,2,3);
var result=c.area();
Objects as Associative Arrays
Property of an object is usually accessed using the dot operator
Obj.prop_name;
JavaScript allows us to access the property of an object using the array notation as follows:
Obj_name[‘propertyname’]
Ex: if x is property of object p, It is accessed as p[‘x’]
Built-in objects/Predefined objects
Javascript provides built-in objects such as Array,Date,Math,String Objects
Javascript allows us to access contents of web pages with the help of DOM(DocumentObject
Model) objects such as window object,location object,history object,navigator object,document
object.
Date Objects:
Date objects are created with the new and Date() constructor.
Date()
Date(year, month, day, hours, minutes, seconds, milliseconds)
Date(milliseconds)
Date(date string) Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1,
1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and
day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since
January 1, 1970)
Math Object:
Math object allows you to perform mathematical tasks on numbers.
ex: Math.PI
Math.round(4.7) Method Description
abs(x) Returns the absolute value of x
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x (x is in radians)
floor(x) Returns the value of x rounded down to its nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x, y, z, ..., n) Returns the number with the highest value
min(x, y, z, ..., n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
RegularExpressions:
A regular expression is an object that describes a pattern of characters that specifies a rule.
Regular expressions are used to perform pattern-matching , search and replace functions on
text.
Regular expression using a literal
var exp=/pattern/flags;
Regular expression using a constructor
var exp=new RegExp(“pattern”,”flags”);
Flags:
icase-insensitive matching
gPerform a global match
mPerform multiline matching
Metacharacters:
Meta characters are characters with a special meaning.
These are used while creating patterns for Regular expressions
Quantifiers
+ one or more occurences
* Zero or more occurences
</html>
// look for “HTML"
var patt2 = /HTML/g;
result2 = patt2.exec(str);
result4 = patt2.test(str);
<!DOCTYPE html>
<html>
<body>
<p>Search a string for "JavaScript", and display the position of the match:</p>
<script>
var str = "Know about Javascript! javascript";
var s=str.search(/JavaScript/i);
document.write("searching pattern string "+s+"<br>");
var n = str.match(/JavaScript/ig);
document.write("pattern matching string "+n);
</script>
Example:
</script>
<html>
<head> </head>
<script language="JavaScript"> <body>
function myFunction() { <p>Do a global search, and test for "Hello"
var str = "Hello world!";
and "W3Schools" in a string:</p>
// look for "Hello"
var patt = /Hello/g; <button onclick="myFunction()">Try
var result = patt.exec(str); it</button><br>
var result3= patt.test(str); Using exec()
// look for “HTML"
<p id="demo"></p>
var patt2 = /HTML/g;
result2 = patt2.exec(str); Using test()
result4 = patt2.test(str); <p id="demo2"></p>
document.getElementById("demo").innerHTML = result
+ "<br>" + result2;
document.getElementById("demo2").innerHTML = result3
</body>
+ "<br>" + result4; </html>
}
JavaScript HTML DOM
Javascript allows us to access contents of web pages.
The components of web page are represented by objects that are organized in hierarchical structure
called Document Object Model(DOM)
These objects have properties and methods that can be used to work with web pages.
Window Object:
It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the
window object
Global variables are properties of the window object
Global functions are methods of the window object
Even the document object (of the HTML DOM) is a property of the window object.
Method Description
alert(msg) displays the alert box containing message with ok button.
confirm(msg) displays the confirm dialog box containing message with ok and
cancel button.
prompt(msg,[input]) 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.
blur() Removes focus from the window
focus() Gives focus to this window
stop() Stops the current download
moveTo(x,y) Moves the window to the specified screen coordinates
resizeTo(x,y) Resizes an entire window to the specified outer height and width
Example
<!DOCTYPE html>
<html>
<body>
<h2>The window Object</h2>
<script>
function f1()
{
window.open(“simple.html”);
}
function msg(){
alert("Hello Alert Box");
}
function msg1(){
confirm("Do u want to proceed");
}
</script>
</body>
<input type=button value="open" onclick="f1()">
<input type=button value="click" onclick="msg()">
<input type=button value="confirm" onclick="msg1()">
Location Object:
Location encapsulates the current URL that is displayed in the visitors browser.
Properties in location object are
location object can be used to get the current page address (URL)
href returns the href (URL) of the current page
hostname returns the domain name of the web host
pathname returns the path and filename of the current page
protocol returns the web protocol used (http: or https:)
assign() loads a new document
Methods:
reload() : current URL is reloaded,equivalent to pressing browsers refresh button
replace(URL) :loads the specified URL by replacing current one
Ex: location.replace(http://www.google.com);
location.reload();
<!DOCTYPE html>
<html>
<body>
<h3>The window.location object properties</h3>
<script>
document.write("The full URL of this page is:<br>" + window.location.href+"<br>");
document.write("Page hostname is " + window.location.hostname+"<br>");
document.write("Page path is " + window.location.pathname+"<br>");
document.write("Page protocol is " + window.location.protocol+"<br>");
</script>
</body>
History object:
window.history object contains the browsers history.
Methods
history.back() method loads the previous URL in the history list.
history.forward() method loads the next URL in the history list.
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser
<html>
<head>
<script>
function goForward() {
window.history.forward()
}
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value=“Forward" onclick="goForward()">
</body>
</html>
Navigator object:
window.navigator object contains information about the visitor's browser.
navigator.appName-returns the application name of the browser
navigator.appCodeName-returns the application code name of the browser
navigator.platform-returns the browser platform (operating system)
navigator.product property returns the product name of the browser engine(Most browsers returns
"Gecko" as product name)
navigator.appVersion property returns version information about the browser
navigator.cookieEnabled property returns true if cookies are enabled, otherwise false
<!DOCTYPE html>
<html>
<body>
<h2>The Navigator Object</h2>
<script>
document.write("navigator.cookieEnabled is " + navigator.cookieEnabled+"<br>");
document.write("navigator.appName is " + navigator.appName+"<br>");
document.write("navigator.appCodeName is " + navigator.appCodeName+"<br>");
document.write("navigator.product is " + navigator.product+"<br>");
</script>
</body>
</html>
Document object
The HTML DOM document object is the owner of all other objects in your web page.
The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
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.
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.
<!DOCTYPE html>
<html>
<body>
<h3>Accessing field value by document object</h3>
<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"/><br>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h3>Methods of document object</h3>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
document.write(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form> 64
</body>
</html>
Javascript Events:
--Javascript identifies an event and takes an action by executing some piece of code.The procedure of
taking actions is called event handling.
--The specific javascript code that takes the action(i.e.,handles the event) is called event handler.
--An event handler may be any valid javascript statement,the handler of an event is usually provided as a
function.
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
Mouse Events
Event name Event handler(property used for Description
event)
click Onclick When mouse click on an element
mouseover Onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Window/Document events
Event name Event handler Description
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser
unloads it
resize onresize When the visitor resizes the window of the browser
Form events
Keyboard events
Examples:
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
<input type="text" id="input1" onfocus="focusevent()"/>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<body onload="window.alert('Page successfully loaded');">
DHTML/Dynamic HTML with javascript
etc fields.
Example: Simple Form validation
<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=“simple.html"
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 Can Validate Numeric Input: // If x is Not a Number or less than one or
<!DOCTYPE html> greater than 10
<html> if (isNaN(x) || x < 1 || x > 10) {
<body bgcolor=“pink”>
text = "Input not valid";
<h2>JavaScript Can Validate Input</h2>
<p>Please input a number between 1 and 10:</p>
} else
<input id="numb"> {
<button type="button" text = "Input OK";
onclick="myFunction()">Submit</button> }
document.getElementById("demo").innerHTML
<p id="demo"></p>
= text;
<script>
}
function myFunction() {
var x, text; </script>
</body>
// Get the value of the input field with </html>
id="numb"
x = document.getElementById("numb").value;
Automatic HTML form validation: If a form field (fname) is empty, the required attribute prevents this form
from being submitted
<!DOCTYPE html>
<html>
<body>
<h3>Automatic Form validation</h3>
<form action=“simple.html" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>
If we click submit without filling text field it displays as below
If the text field is filled and when clicks on submit it redirects to linked file
Program: Validating the Registration form using Regular expressions
<html>
<head><h1>Form validation using Regular expression</h1>
<script>
function validateform(){
var usr=/^[A-Za-z]\w{7,14}$/;
var name1=document.myform.name.value;
var pwd=/\w{7,14}$/;
var pwd1=document.myform.password.value;
if (!usr.test(name1)){
alert("name should not be empty ,should start with alphabets and length should be 7 to 14 only");
return false;
}
if(!pwd.test(pwd1))
{
alert("enter correct password");
return false;
}
document.write("registered successfully");
}
</script>
</head>
<body>
<form style="font-size:30px" name="myform" method="post" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password" required><br>
<input style="font-size:30px" type="submit" value="register">
</form>
</body>
</html>