SlideShare a Scribd company logo
1 of 95
JavaScript
was developed by Netscape, was originally named Mocha but soon was renamed LiveScript
In late 1995 Live Script became a joint venture of Netscape and Sun Microsystems, then
renamed as JavaScript.
What is JavaScript
JavaScript is a lightweight, interpreted programming language
Designed for creating network-centric applications
Complementary to and integrated with Java
Complementary to and integrated with HTML
Open and cross-platform
JavaScript is loosely based on Java and it is built into all the major modern browsers.
JavaScript can be divided into three parts:
1. the core JavaScript
2. client side JavaScript
3. server side JavaScript
the core JavaScript : is the heart of the language, it includes operators,
expressions, statements, and subprograms.
client side JavaScript: is a collection of objects that support the control of a
browser and interactions with users
Server-side JavaScript : is a collection of objects that make the language useful on a
Web server
difference between Java and JavaScript
The two languages are completely unrelated. they could hardly be more different
Java is a object-oriented languages; Java Script is Object-based Language.
Java is strongly typed, while JavaScript is weakly typed.
JavaScript has first-class functions; Java lacks them.
Java is class-based; JavaScript is prototype-based.
Java is distributed as compiled bytecode; JavaScript is distributed in its source
code.
JavaScript Syntax
A JavaScript consists of JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
The <script> tag alert the browser program to begin interpreting all the text
between these tags as a script.
<script language="JavaScript" type="text/ javascript">
JavaScript code
</script>
It as two important attributes:
language: This attribute specifies what scripting language you are using.
type: This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".
Where to put the java Script
JavaScripts in a page will be executed immediately while the page loads into the
browser.
You can put javascript any where in the document.
Scripts in the header section: scripts to be executed when they are called,or
when an event is trigged.
<html>
<head>
<script type=“text/javascript”>
---------
</script>
</head>
</html>
Scripts in the body section: scripts to be executed when the page loads.
<html>
<head>
<body>
<script type=“text/javascript”>
………..
</script>
</body>
</html>
Scripts in both body and header section: you can place an unlimited number of
scripts in your document.
We can also write java script in a separate file with .js extension. To call external
javascript file we use an attribute in script tag that is src.
JavaScript Datatypes
JavaScript allows
three primitive data types
1.Numbers eg. 123, 120.50 etc.
2.Strings of text e.g. "This text string" etc.
3.Boolean e.g. true or false.
two trivial data types
1.null
2.undefined
JavaScript Variables
Variables is a container for information you want to store.
Rules for variable names
Variable name are case sensitive.
They must begin with letter or underscore character.
should not use any of the JavaScript reserved keyword as variable name.
Declaring a Variables : variable are declared using var keyword.
example: var money;
here semicolon is optional.
You can also create a variable without var statement.
money=100;
Assigning value to variable
Var strname=“hello”
OR
Strname=“hello”
Variable Scope
The scope of a variable is the region of your program in which it is defined.
JavaScript variable will have only two scopes.
1. Global Variables: A global variable has global scope which means it is
defined everywhere in your JavaScript code.
2. Local Variables: A local variable will be visible only within a function
where it is defined. Function parameters are always local to that function.
JavaScript Reserved Words
They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names
Arithmetic Operators supported by JavaScript
+ Adds two operands
- Subtracts second operand from the first
* Multiply both operands
/ Divide numerator by denumerator
% Modulus Operator and remainder of after an integer division .
Comparison Operators supported by JavaScript
==,>,<,>=,=<
Logical Operators supported by JavaScript
&& (Logical AND ),|| (Logical OR),! (Logical NOT)
Bitwise Operators supported by JavaScript
&(Bitwise AND ),|(Bitwise OR), ^ (Bitwise XOR) , ~ (Bitwise NOT)
Assignment Operators supported by JavaScript
= , += , -= , *= , /= , %=
Conditional Operator
typeof Operator
The typeof is a unary operator that is placed before its single operand, which
can be of any type. Its value is a string indicating the data type of the operand.
Control statements
if statement
Syntax
if (expression){
Statement(s) to be executed if expression is true
}
if...else statement
Syntax
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
if...else if... Statement
Syntax
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}else
{
Statement(s) to be executed if no expression is true
switch statement
Syntax
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Java Script Popup Boxes
Alert Box
An alert dialog box is mostly used to give a warning message to the users.
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>
Confirmation Dialog Box
A confirmation dialog box is mostly used to take user's consent on any option. It
displays a dialog box with two buttons: OK and Cancel.
<script language="javascript">
function respond()
{
var retVal = confirm("are u sure to continue");
if(retVal == true)
{
window.location="../first.html";
}
else{alert("you have canceled the redirection");}
}
</script>
Prompt Dialog Box
Prompt bob is often used if you want the user to input a value before entering a
page
<head>
<script type="text/javascript">
<!--
var retVal = prompt(“someText", “defaultvalue");
alert("You have entered : " + retVal );
//-->
</script>
</head>
Java Script Functions
The most common way to define a function in JavaScript is by using the function
keyword, followed by a unique function name, a list of parameters (that might be
empty), and a statement block surrounded by curly braces.
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
A function contain some code that will be executed only by an event or a call to
that function.
example
<html>
<head>
<script type=“text/javascript”>
function displaymessage()
{
alert(“hello world”);
}
</script>
</head>
<body>
<form>
<input type=“button” value=“clickme” onclick=“displaymessage()”>
</form>
</body>
</html>
JavaScript loops
while Loop
while (expression){
Statement(s) to be executed if expression is true
}
do...while Loop
do{
Statement(s) to be executed;
} while (expression);
for Loop
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
for...in Loop
for (variablename in object)
{
statement or block to execute
}
Events
Every element on a web page has certain Events which can trigger javascript
functions.
Example of events
1.A mouse clicks
2.A web page loading or an image loading
3.Mouse over a hot spot on the web page
4.selecting an input box in an HTML form
5.submitting an HTML form
6.A key Stroke.
Types of events
1.Window Events(Onload and onunload )
2.Form Events(OnFocus ,onBlur and onChange,onsubmit)
3. Keyboard Events(onkeydown, onkeypress, onkeyup)
4. Mouse Events(onMouseOver and onMouseOut)
Onload and onunload events
• The onload and onunload events are trigged when the unters or
leaves the page.
• The onload attribute can be used to check the visitor's browser type
and browser version, and load the proper version of the web page
based on the information.
• Syntax
• <element onload="script">
OnFocus ,onBlur and onChange
onFocus: The onfocus attribute fires the moment that the element gets focus.
onBlur: The onblur attribute fires the moment that the element loses focus.
onChange :The onchange attribute fires the moment when the value of the element is
changed.
These events are often used in combination with validation of form fields.
Syntax
<element onfocus="script">
<element onblur="script">
<element onchange="script">
onsubmit
The onsubmit attribute fires when a form is submitted.
The onsubmit event is used to validate all form fields before submitting it.
Syntax
<form onsubmit="script">
onkeydown, onkeypress, onkeyup
The onkeydown attribute fires when the user is pressing a key.
The onkeypress attribute fires when the user presses a key.
The onkeyup attribute fires when the user releases a key.
syntax
<element onkeydown=" script " onkeypress=" script " onkeyup=" script ">
onMouseOver and onMouseOut
The onmouseover attribute fires when the mouse pointer moves over an element.
Syntax
<element onmouseover="script">
The onmouseout attribute fires when the mouse pointer moves out of an element.
syntax
<element onmouseout="script">
Objects in JavaScript
1. Array object
2. String object
3. Math object
4. Date object
Arrays
An array is a special variable, which can hold more than one value, at a time.
An array can be defined in three ways.
The following code creates an Array object called myCars:
1:
var myCars=new Array(); // regular array
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
3:
var myCars=["Saab","Volvo","BMW"];
Access an Array
• The following code line:
• document. write(myCars[0]);will result in the following output:
Saab
Modify Values in an Array
• To modify a value in an existing array, just add a new value to the
array with a specified index number:
• myCars[0]="Opel";
• Now, the following code line:
• document.write(myCars[0]);
• will result in the following output:
Opel
Predefined methods
Join two arrays - concat()
<html>
<body>
<script type="text/javascript">
var parents = ["Jani", "Tove"];
var children = ["Cecilie", "Lone"];
var family = parents.concat(children);
document.write(family);
</script>
</body>
</html>
Code for joining three arrays
<html>
<body>
<script type="text/javascript">
var parents = ["Jani", "Tove"];
var brothers = ["Stale", "Kai Jim", "Borge"];
var children = ["Cecilie", "Lone"];
var family = parents.concat(brothers, children);
document.write(family);
</script>
</body>
</html>
Join all elements of an array into a string - join()
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));
</script>
</body>
</html>
Remove the last element of an array - pop()
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.pop() + "<br />");
document.write(fruits + "<br />");
document.write(fruits.pop() + "<br />");
document.write(fruits);
</script>
</body>
</html>
Add new elements to the end of an array - push()
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango","ramana"];
document.write(fruits.push("Kiwi") + "<br />");
document.write(fruits.push("Lemon","Pineapple") + "<br />");
document.write(fruits);
</script>
</body>
</html>
Reverse the order of the elements in an array - reverse()
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.reverse());
</script>
</body>
</html>
Sort an array (alphabetically and ascending) - sort()
<html>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.sort());
</script>
</body>
</html>
String Object
The String object is used to manipulate a stored piece of text.
String objects are created with new String()
Syntax:
var txt = new String(string);
or more simply:
var txt = string;
String Object Properties
Length Returns the length of a string
Return the number of characters in a string
<script type="text/JavaScript">
var txt = "Hello World!";
document.write(txt.length);
</script>
String Object Methods
Method
charAt(): Returns the character at the specified index
Example:
Return the first and last character of a string:
<script type="text/javascript">
var str = "Hello world!";
document.write("First character: " + str.charAt(0) + "<br />");
document.write("Last character: " + str.charAt(str.length-1));
</script>
charCodeAt():Returns the Unicode of the character at the specified index
Return the Unicode of the first and last character in a string:
<script type="text/javascript">
var str = "Hello world!";
document.write("First character: " + str.charCodeAt(0) + "<br />");
document.write("Last character: " + str.charCodeAt(str.length-1));
</script>
concat():Joins two or more strings, and returns a copy of the joined strings
Join two strings:
<script type="text/javascript">
var str1="Hello ";
var str2="world!";
document.write(str1.concat(str2));
</script>
fromCharCode() Converts Unicode values to characters
syntax:
String.fromCharCode(n1, n2, ..., nX)
Convert Unicode values to characters:
<script type="text/javascript">
document.write(String.fromCharCode(72,69,76,76,79));
</script>
indexOf():Returns the position of the first found occurrence of a specified value in
a string
<script type="text/javascript">
var str="Hello world!";
document.write(str.indexOf("d") + "<br />");
document.write(str.indexOf("WORLD") + "<br />");
document.write(str.indexOf("world"));
</script>
lastIndexOf():Returns the position of the last found occurrence of a specified value
in a string
<script type="text/javascript">
var str="Hello world!";
document.write(str.lastIndexOf("d") + "<br />");
document.write(str.lastIndexOf("WORLD") + "<br />");
document.write(str.lastIndexOf(“l"));
</script>
toLowerCase():Converts a string to lowercase letters
<script type="text/javascript">
var str="Hello World!";
document.write(str.toLowerCase());
</script>
toUpperCase():Converts a string to uppercase letters
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
substr():Extracts the characters from a string, beginning at a specified start
position, and through the specified number of character
<script type="text/javascript">
var str="Hello world!";
document.write(str.substr(3)+"<br />");
document.write(str.substr(3,4));
</script>
replace():Searches for a match between a substring (or regular expression) and a
string, and replaces the matched substring with a new substring
<script type="text/javascript">
var str="Visit Microsoft!";
document.write(str.replace("Microsoft", “jntu"));
</script>
String HTML Wrapper Methods
The HTML wrapper methods return the string wrapped inside the appropriate
HTML tag.
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fontcolor() Displays a string using a specified color
fontsize() Displays a string using a specified size
italics() Displays a string in italic
small() Displays a string using a small font
strike() Displays a string with a strikethrough
link() Displays a string as a hyperlink
sub() Displays a string as subscript text
sup() Displays a string as superscript text
<html>
<body>
<script type="text/javascript">
var txt = "Hello World!";
document.write("<p>Big: " + txt.big() + "</p>");
document.write("<p>Small: " + txt.small() + "</p>");
document.write("<p>Bold: " + txt.bold() + "</p>");
document.write("<p>Italic: " + txt.italics() + "</p>");
document.write("<p>Strike: " + txt.strike() + "</p>");
document.write("<p>Fontcolor: " + txt.fontcolor("green") + "</p>");
document.write("<p>Fontsize: " + txt.fontsize(6) + "</p>");
document.write("<p>Subscript: " + txt.sub() + "</p>");
document.write("<p>Superscript: " + txt.sup() + "</p>");
document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>");
document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>");
</script>
</body>
</html>
Math Object
The Math object allows you to perform mathematical tasks.
All properties/methods of Math can be called by using Math as an object, without
creating it.
Syntax:
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
Math Object Methods
abs(x):Returns the absolute value of x
<script type="text/javascript">
document.write(Math.abs(7.25) + "<br />");
document.write(Math.abs(-7.25) + "<br />");
document.write(Math.abs(null) + "<br />");
document.write(Math.abs("Hello") + "<br />");
document.write(Math.abs(2+3));
</script>
ceil(x):Returns x, rounded upwards to the nearest integer
<script type="text/javascript">
document.write(Math.ceil(0.60) + "<br />");
document.write(Math.ceil(0.40) + "<br />");
document.write(Math.ceil(5) + "<br />");
document.write(Math.ceil(5.1) + "<br />");
document.write(Math.ceil(-5.1) + "<br />");
document.write(Math.ceil(-5.9));
</script>
cos(x):Returns the cosine of x
<script type="text/javascript">
document.write(Math.cos(3) + "<br />");
document.write(Math.cos(-3) + "<br />");
document.write(Math.cos(0) + "<br />");
document.write(Math.cos(Math.PI) + "<br />");
document.write(Math.cos(2*Math.PI));
</script>
exp(x):Returns the value of E
<script type="text/javascript">
document.write(Math.exp(1) + "<br />");
document.write(Math.exp(-1) + "<br />");
document.write(Math.exp(5) + "<br />");
document.write(Math.exp(10) + "<br />");
</script>
floor(x):Returns x, rounded downwards to the nearest intege
<script type="text/javascript">
document.write(Math.floor(0.60) + "<br />");
document.write(Math.floor(0.40) + "<br />");
document.write(Math.floor(5) + "<br />");
document.write(Math.floor(5.1) + "<br />");
document.write(Math.floor(-5.1) + "<br />");
document.write(Math.floor(-5.9));
</script>
log(x):Returns the natural logarithm (base E) of x
<script type="text/javascript">
document.write(Math.log(2.7183) + "<br />");
document.write(Math.log(2) + "<br />");
document.write(Math.log(1) + "<br />");
document.write(Math.log(0) + "<br />");
document.write(Math.log(-1));
</script>
max(x,y,z,...,n):Returns the number with the highest value
min(x,y,z,...,n): Returns the number with the lowest value
<script type="text/javascript">
document.write(Math.max(5,10) + "<br />");
document.write(Math.max(0,150,30,20,38) + "<br />");
document.write(Math.max(-5,10) + "<br />");
document.write(Math.max(-5,-10) + "<br />");
document.write(Math.max(1.5,2.5));
</script>
Pow(x,y):Returns the value of x to the power of y
<script type="text/javascript">
document.write(Math.pow(0,0) + "<br />");
document.write(Math.pow(0,1) + "<br />");
document.write(Math.pow(1,1) + "<br />");
document.write(Math.pow(1,10) + "<br />");
document.write(Math.pow(7,2) + "<br />");
document.write(Math.pow(-7,2) + "<br />");
document.write(Math.pow(2,4));
</script>
random():Returns a random number between 0 and 1
<script type="text/javascript">
//return a random number between 0 and 1
document.write(Math.random() + "<br />");
//return a random integer between 0 and 10
document.write(Math.floor(Math.random()*11));
</script>
round(x):Rounds x to the nearest integer
<script type="text/javascript">
document.write(Math.round(0.60) + "<br />");
document.write(Math.round(0.50) + "<br />");
document.write(Math.round(0.49) + "<br />");
document.write(Math.round(-4.40) + "<br />");
document.write(Math.round(-4.60));
</script>
sqrt(x):Returns the square root of x
<script type="text/javascript">
document.write(Math.sqrt(0) + "<br />");
document.write(Math.sqrt(1) + "<br />");
document.write(Math.sqrt(9) + "<br />");
document.write(Math.sqrt(0.64) + "<br />");
document.write(Math.sqrt(-9));
</script>
Date Object
The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Date Object Methods
getDate():Returns the day of the month (from 1-31)
<script type="text/javascript">
var d = new Date();
document.write(d.getDate());
</script>
Return the day of the month from a specific date:
<script type="text/javascript">
var d = new Date("July 21, 1983 01:15:00");
document.write(d.getDate());
</script>
getDay():Returns the day of the week (from 0-6)
<script type="text/javascript">
var d = new Date();
document.write(d.getDay());
</script>
Return the name of the weekday (not just a number):
<script type="text/javascript">
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("Today is " + weekday[d.getDay()]);
</script>
getFullYear():Returns the year (four digits)
<script type="text/javascript">
var d = new Date();
document.write(d.getFullYear());
</script>
Return the four-digit year from a specific date:
<script type="text/javascript">
var d = new Date("July 21, 1983 01:15:00");
document.write("I was born in " + d.getFullYear());
</script>
getHours():Returns the hour (from 0-23)
<script type="text/javascript">
var d = new Date();
document.write(d.getHours());
</script>
Return the hour from a specific date and time:
<script type="text/javascript">
var d = new Date("July 21, 1983 01:15:00");
document.write(d.getHours());
</script>
getMilliseconds():Returns the milliseconds (from 0-999)
<script type="text/javascript">
var d = new Date();
document.write(d.getMilliseconds());
</script>
Return the milliseconds from a specific date and time:
<script type="text/javascript">
var d = new Date("July 21, 1983 01:15:00");
document.write(d.getMilliseconds());
</script>
es():Returns the minutes (from 0-59)
h():Returns the month (from 0-11)
ds():Returns the seconds (from 0-59)
:Returns the number of milliseconds since midnight Jan 1, 1970
oneOffset():Returns the time difference between GMT and local time, in minutes
ate():Returns the day of the month, according to universal time (from 1-31)
ay():Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear():Returns the year, according to universal time (four digits)
getUTCHours()Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds(): Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes()Returns the minutes, according to universal time (from 0-59)
getUTCMonth()Returns the month, according to universal time (from 011)
getUTCSeconds()Returns the seconds, according to universal time (from 0-59)
setDate()Sets the day of the month (from 1-31)
<script type="text/javascript">
var d = new Date();
d.setDate(15);
document.write(d);
</script>
setFullYear()Sets the year (four digits)
<script type="text/javascript">
var d = new Date();
d.setFullYear(2020);
document.write(d);
</script>
Set the date to November 3, 1992
<script type="text/javascript">
var d=new Date();
d.setFullYear(1992,10,3);
document.write(d);
</script>
setHours()Sets the hour (from 0-23)
Date.setHours(hour,min,sec,millisec)
<script type="text/javascript">
var d = new Date();
d.setHours(15);
document.write(d);
</script>
Set the time to 15:35:01:
<script type="text/javascript">
var d = new Date();
d.setHours(15,35,1);
document.write(d);
</script>
setMilliseconds()Sets the milliseconds (from 0-999)
Set the milliseconds to 192:
<script type="text/javascript">
var d = new Date();
d.setMilliseconds(192);
document.write(d);
</script>
setMinutes()Set the minutes (from 0-59)
Date.setMinutes(min,sec,millisec)
Set the minutes to 01:
<script type="text/javascript">
var d = new Date();
d.setMinutes(1);
document.write(d);
</script>
Out Put:
Sun Aug 15 2010 19:01:08 GMT+0530 (India Standard Time)
setMonth()Sets the month (from 0-11)
Date.setMonth(month,day)
Set the month to 0 (January):
<script type="text/javascript">
var d = new Date();
d.setMonth(0);
document.write(d);
</script>
Set the month to 0 (January) and the day to 20:
<script type="text/javascript">
var d = new Date();
d.setMonth(0,20);
document.write(d);
</script>
setSeconds()Sets the seconds (from 0-59)
Date.setSeconds(sec,millisec)
Set the seconds to 01:
<script type="text/javascript">
var d = new Date();
d.setSeconds(1);
document.write(d);
</script>
setTime()Sets a date and time by adding or subtracting a specified number of
milliseconds to/from midnight January 1, 1970
Date.setTime(millisec)
<script type="text/javascript">
var d = new Date();
d.setTime(77771564221);
document.write(d);
</script>
setUTCDate()Sets the day of the month, according to universal time (from 1-31)
setUTCFullYear()Sets the year, according to universal time (four digits)
setUTCHours()Sets the hour, according to universal time (from 0-23)
setUTCMilliseconds()Sets the milliseconds, according to universal time (from 0-
999)
setUTCMinutes()Set the minutes, according to universal time (from 0-59)
setUTCMonth()Sets the month, according to universal time (from 0-11)
setUTCSeconds()Set the seconds, according to universal time (from 0-59)
Opening a New Window
To open a new window, you will need to use yet another ready-made JavaScript
function.
Here is what it looks like:
window.open('url to open','window name','attribute1,attribute2')
1.'url to open'
This is the web address of the page you wish to appear in the new window.
2. 'window name'
You can name your window whatever you like, in case you need to make a reference to
the window later.
3. 'attribute1,attribute2'
As with alot of other things, you have a choice of attributes you can adjust.
Window Attributes
Below is a list of the attributes you can use:
1. width=300
Use this to define the width of the new window.
2. height=200
Use this to define the height of the new window.
3. resizable=yes or no
Use this to control whether or not you want the user to be able to resize the
window.
4. scrollbars=yes or no
This lets you decide whether or not to have scrollbars on the window.
5. toolbar=yes or no
Whether or not the new window should have the browser navigation bar at the
top (The back, foward, stop buttons..etc.).
6. location=yes or no
Whether or not you wish to show the location box with the current url (The place
to type http://address).
7. directories=yes or no
Whether or not the window should show the extra buttons. (what's cool,
personal buttons, etc...).
8. status=yes or no
Whether or not to show the window status bar at the bottom of the window.
9. menubar=yes or no
Whether or not to show the menus at the top of the window (File, Edit, etc...).
10. copyhistory=yes or no
Whether or not to copy the old browser window's history list to the new
window.
<HTML>
<HEAD>
<TITLE>JavaScript Example 5</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1>This is a new window!</H1>
</CENTER>
<P>
<CENTER>
<FORM>
<input type="button" value="facebook"onclick="window.open('http://www.facebook.com',
'windowname1', 'width=200, height=77'); ">
</FORM>
</CENTER>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>JavaScript Example 5</TITLE> </HEAD>
<BODY>
<CENTER> <H1>This is a new window!</H1> </CENTER>
<P>
<CENTER>
<FORM>
<INPUT type="button" value="Close Window" onClick="window.close()"> </FORM>
</CENTER>
</BODY>
</HTML>
<html>
<head>
<script type="text/javascript">
function open_win()
{
window.open("http://www.w3schools.com","_blank","toolbar=yes, location=yes, directories=no,
status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400,
height=400");
}
</script>
</head>
<body>
<form>
<input type="button" value="Open Window" onclick="open_win()">
</form>
</body>
</html>
Data Validations
Login.html
<html>
<head>
<title>Login</title>
<script type="text/javascript">
function validate(form){
var userName = form.Username.value;
var password = form.Password.value;
if (userName.length === 0) {
alert("You must enter a username.");
return false;
}
if (password.length === 0) {
alert("You must enter a password.");
return false;
} return true; } </script> </head>
<body>
<h1>Login Form</h1>
<form method="post" action="Process.html" onsubmit="return validate(this);">
Username: <input type="text" name="Username" size="10"><br/>
Password: <input type="password" name="Password" size="10"><br/>
<input type="submit" value="Submit"> <input type="reset" value="Reset Form">
</p>
</form>
</body>
</html>
<html>
<head>
<title>Login</title>
<script type="text/javascript">
function validate(form)
{
var userName = form.Username.value;
var password = form.Password.value;
var number=form.PhoneNumber.value;
var str=form.Email.value;
if (userName.length < 6)
{
alert("You must enter 6 char a username.");
form.Username.focus();
return false;
}
if (password.length < 6)
{
alert("You must enter a min 6 char password.");
form.Password.focus();
return false;
}
if(number.length < 10)
{
alert("enter correct phone number");
form.PhoneNumber.focus();
return false;
}
var p1,p2,d;
p1=str.indexOf('@');
p2=str.indexOf('.');
d=p2-p1;
if(p1==0||p2==0||d<=1)
{
alert("enter correct email id");
form.Email.focus();
return false;
}
return true;
}
</script>
</head>
<body bgcolor="gerren" >
<h1>Login Form</h1>
<form method="post" action="http://www.gmail.com"
onsubmit="return validate(this);">
Username: <input type="text" name="Username" size="10"><br/><br/>
Password: <input type="password" name="Password" size="10"><br/>
Phone Number: <input type="text" name="PhoneNumber" size="10"><br/>
E-mail: <input type="text" name="Email" size="20"><br/>
<input type="submit" value="Submit">
<input type="reset" value="Reset Form">
</p>
</form>
</body>
</html>

More Related Content

What's hot (20)

Intro to react native
Intro to react nativeIntro to react native
Intro to react native
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Getting Started with React.js
Getting Started with React.jsGetting Started with React.js
Getting Started with React.js
 
React native
React nativeReact native
React native
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Reactjs
ReactjsReactjs
Reactjs
 
WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
React js
React jsReact js
React js
 
React hooks
React hooksReact hooks
React hooks
 
React JS
React JSReact JS
React JS
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Reactjs
Reactjs Reactjs
Reactjs
 

Similar to JavaScript: The Complete Guide in 40 Characters

Similar to JavaScript: The Complete Guide in 40 Characters (20)

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Java script
Java scriptJava script
Java script
 
Java scipt
Java sciptJava scipt
Java scipt
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
Basics of Javascript
Basics of Javascript Basics of Javascript
Basics of Javascript
 
Java script
Java scriptJava script
Java script
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
Java script
Java scriptJava script
Java script
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
Javascript
JavascriptJavascript
Javascript
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 

More from Rajkiran Mummadi (17)

Servlets
ServletsServlets
Servlets
 
Php
PhpPhp
Php
 
Javabeans .pdf
Javabeans .pdfJavabeans .pdf
Javabeans .pdf
 
Java beans
Java beansJava beans
Java beans
 
Ajax.pdf
Ajax.pdfAjax.pdf
Ajax.pdf
 
Google glasses
Google glassesGoogle glasses
Google glasses
 
Environmental hazards
Environmental hazardsEnvironmental hazards
Environmental hazards
 
Wcharging
WchargingWcharging
Wcharging
 
Wireless charging
Wireless chargingWireless charging
Wireless charging
 
Standard bop
Standard bopStandard bop
Standard bop
 
Russian technology in indian banking system 1
Russian technology in indian banking system 1Russian technology in indian banking system 1
Russian technology in indian banking system 1
 
Ai presentation
Ai presentationAi presentation
Ai presentation
 
Loon
LoonLoon
Loon
 
Triggers
TriggersTriggers
Triggers
 
autonomous cars
autonomous carsautonomous cars
autonomous cars
 
ET3
ET3ET3
ET3
 
demonetisation
demonetisationdemonetisation
demonetisation
 

Recently uploaded

Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

JavaScript: The Complete Guide in 40 Characters

  • 1. JavaScript was developed by Netscape, was originally named Mocha but soon was renamed LiveScript In late 1995 Live Script became a joint venture of Netscape and Sun Microsystems, then renamed as JavaScript. What is JavaScript JavaScript is a lightweight, interpreted programming language Designed for creating network-centric applications Complementary to and integrated with Java Complementary to and integrated with HTML Open and cross-platform JavaScript is loosely based on Java and it is built into all the major modern browsers.
  • 2. JavaScript can be divided into three parts: 1. the core JavaScript 2. client side JavaScript 3. server side JavaScript the core JavaScript : is the heart of the language, it includes operators, expressions, statements, and subprograms. client side JavaScript: is a collection of objects that support the control of a browser and interactions with users Server-side JavaScript : is a collection of objects that make the language useful on a Web server
  • 3. difference between Java and JavaScript The two languages are completely unrelated. they could hardly be more different Java is a object-oriented languages; Java Script is Object-based Language. Java is strongly typed, while JavaScript is weakly typed. JavaScript has first-class functions; Java lacks them. Java is class-based; JavaScript is prototype-based. Java is distributed as compiled bytecode; JavaScript is distributed in its source code.
  • 4. JavaScript Syntax A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page. The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. <script language="JavaScript" type="text/ javascript"> JavaScript code </script> It as two important attributes: language: This attribute specifies what scripting language you are using. type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
  • 5. Where to put the java Script JavaScripts in a page will be executed immediately while the page loads into the browser. You can put javascript any where in the document. Scripts in the header section: scripts to be executed when they are called,or when an event is trigged. <html> <head> <script type=“text/javascript”> --------- </script> </head> </html>
  • 6. Scripts in the body section: scripts to be executed when the page loads. <html> <head> <body> <script type=“text/javascript”> ……….. </script> </body> </html> Scripts in both body and header section: you can place an unlimited number of scripts in your document. We can also write java script in a separate file with .js extension. To call external javascript file we use an attribute in script tag that is src.
  • 7. JavaScript Datatypes JavaScript allows three primitive data types 1.Numbers eg. 123, 120.50 etc. 2.Strings of text e.g. "This text string" etc. 3.Boolean e.g. true or false. two trivial data types 1.null 2.undefined
  • 8. JavaScript Variables Variables is a container for information you want to store. Rules for variable names Variable name are case sensitive. They must begin with letter or underscore character. should not use any of the JavaScript reserved keyword as variable name. Declaring a Variables : variable are declared using var keyword. example: var money; here semicolon is optional. You can also create a variable without var statement. money=100;
  • 9. Assigning value to variable Var strname=“hello” OR Strname=“hello” Variable Scope The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes. 1. Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code. 2. Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
  • 10. JavaScript Reserved Words They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names
  • 11. Arithmetic Operators supported by JavaScript + Adds two operands - Subtracts second operand from the first * Multiply both operands / Divide numerator by denumerator % Modulus Operator and remainder of after an integer division . Comparison Operators supported by JavaScript ==,>,<,>=,=< Logical Operators supported by JavaScript && (Logical AND ),|| (Logical OR),! (Logical NOT) Bitwise Operators supported by JavaScript &(Bitwise AND ),|(Bitwise OR), ^ (Bitwise XOR) , ~ (Bitwise NOT)
  • 12. Assignment Operators supported by JavaScript = , += , -= , *= , /= , %= Conditional Operator typeof Operator The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
  • 13. Control statements if statement Syntax if (expression){ Statement(s) to be executed if expression is true } if...else statement Syntax if (expression){ Statement(s) to be executed if expression is true }else{ Statement(s) to be executed if expression is false }
  • 14. if...else if... Statement Syntax if (expression 1) { Statement(s) to be executed if expression 1 is true }else if (expression 2) { Statement(s) to be executed if expression 2 is true }else if (expression 3) { Statement(s) to be executed if expression 3 is true }else { Statement(s) to be executed if no expression is true
  • 15. switch statement Syntax switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s) }
  • 16. Java Script Popup Boxes Alert Box An alert dialog box is mostly used to give a warning message to the users. <head> <script type="text/javascript"> <!-- alert("Warning Message"); //--> </script> </head>
  • 17. Confirmation Dialog Box A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel. <script language="javascript"> function respond() { var retVal = confirm("are u sure to continue"); if(retVal == true) { window.location="../first.html"; } else{alert("you have canceled the redirection");} } </script>
  • 18. Prompt Dialog Box Prompt bob is often used if you want the user to input a value before entering a page <head> <script type="text/javascript"> <!-- var retVal = prompt(“someText", “defaultvalue"); alert("You have entered : " + retVal ); //--> </script> </head>
  • 19. Java Script Functions The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. <script type="text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script> A function contain some code that will be executed only by an event or a call to that function.
  • 20. example <html> <head> <script type=“text/javascript”> function displaymessage() { alert(“hello world”); } </script> </head> <body> <form> <input type=“button” value=“clickme” onclick=“displaymessage()”> </form> </body> </html>
  • 21. JavaScript loops while Loop while (expression){ Statement(s) to be executed if expression is true } do...while Loop do{ Statement(s) to be executed; } while (expression); for Loop for (initialization; test condition; iteration statement) { Statement(s) to be executed if test condition is true } for...in Loop for (variablename in object) { statement or block to execute }
  • 22. Events Every element on a web page has certain Events which can trigger javascript functions. Example of events 1.A mouse clicks 2.A web page loading or an image loading 3.Mouse over a hot spot on the web page 4.selecting an input box in an HTML form 5.submitting an HTML form 6.A key Stroke. Types of events 1.Window Events(Onload and onunload ) 2.Form Events(OnFocus ,onBlur and onChange,onsubmit) 3. Keyboard Events(onkeydown, onkeypress, onkeyup) 4. Mouse Events(onMouseOver and onMouseOut)
  • 23. Onload and onunload events • The onload and onunload events are trigged when the unters or leaves the page. • The onload attribute can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. • Syntax • <element onload="script">
  • 24. OnFocus ,onBlur and onChange onFocus: The onfocus attribute fires the moment that the element gets focus. onBlur: The onblur attribute fires the moment that the element loses focus. onChange :The onchange attribute fires the moment when the value of the element is changed. These events are often used in combination with validation of form fields. Syntax <element onfocus="script"> <element onblur="script"> <element onchange="script">
  • 25. onsubmit The onsubmit attribute fires when a form is submitted. The onsubmit event is used to validate all form fields before submitting it. Syntax <form onsubmit="script">
  • 26. onkeydown, onkeypress, onkeyup The onkeydown attribute fires when the user is pressing a key. The onkeypress attribute fires when the user presses a key. The onkeyup attribute fires when the user releases a key. syntax <element onkeydown=" script " onkeypress=" script " onkeyup=" script ">
  • 27. onMouseOver and onMouseOut The onmouseover attribute fires when the mouse pointer moves over an element. Syntax <element onmouseover="script"> The onmouseout attribute fires when the mouse pointer moves out of an element. syntax <element onmouseout="script">
  • 28. Objects in JavaScript 1. Array object 2. String object 3. Math object 4. Date object
  • 29. Arrays An array is a special variable, which can hold more than one value, at a time. An array can be defined in three ways. The following code creates an Array object called myCars: 1: var myCars=new Array(); // regular array myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; 2: var myCars=new Array("Saab","Volvo","BMW"); 3: var myCars=["Saab","Volvo","BMW"];
  • 30. Access an Array • The following code line: • document. write(myCars[0]);will result in the following output: Saab
  • 31. Modify Values in an Array • To modify a value in an existing array, just add a new value to the array with a specified index number: • myCars[0]="Opel"; • Now, the following code line: • document.write(myCars[0]); • will result in the following output: Opel
  • 32. Predefined methods Join two arrays - concat() <html> <body> <script type="text/javascript"> var parents = ["Jani", "Tove"]; var children = ["Cecilie", "Lone"]; var family = parents.concat(children); document.write(family); </script> </body> </html>
  • 33. Code for joining three arrays <html> <body> <script type="text/javascript"> var parents = ["Jani", "Tove"]; var brothers = ["Stale", "Kai Jim", "Borge"]; var children = ["Cecilie", "Lone"]; var family = parents.concat(brothers, children); document.write(family); </script> </body> </html>
  • 34. Join all elements of an array into a string - join() <html> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write(fruits.join() + "<br />"); document.write(fruits.join("+") + "<br />"); document.write(fruits.join(" and ")); </script> </body> </html>
  • 35. Remove the last element of an array - pop() <html> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write(fruits.pop() + "<br />"); document.write(fruits + "<br />"); document.write(fruits.pop() + "<br />"); document.write(fruits); </script> </body> </html>
  • 36. Add new elements to the end of an array - push() <html> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango","ramana"]; document.write(fruits.push("Kiwi") + "<br />"); document.write(fruits.push("Lemon","Pineapple") + "<br />"); document.write(fruits); </script> </body> </html>
  • 37. Reverse the order of the elements in an array - reverse() <html> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write(fruits.reverse()); </script> </body> </html>
  • 38. Sort an array (alphabetically and ascending) - sort() <html> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.write(fruits.sort()); </script> </body> </html>
  • 39. String Object The String object is used to manipulate a stored piece of text. String objects are created with new String() Syntax: var txt = new String(string); or more simply: var txt = string;
  • 40. String Object Properties Length Returns the length of a string Return the number of characters in a string <script type="text/JavaScript"> var txt = "Hello World!"; document.write(txt.length); </script>
  • 41. String Object Methods Method charAt(): Returns the character at the specified index Example: Return the first and last character of a string: <script type="text/javascript"> var str = "Hello world!"; document.write("First character: " + str.charAt(0) + "<br />"); document.write("Last character: " + str.charAt(str.length-1)); </script>
  • 42. charCodeAt():Returns the Unicode of the character at the specified index Return the Unicode of the first and last character in a string: <script type="text/javascript"> var str = "Hello world!"; document.write("First character: " + str.charCodeAt(0) + "<br />"); document.write("Last character: " + str.charCodeAt(str.length-1)); </script>
  • 43. concat():Joins two or more strings, and returns a copy of the joined strings Join two strings: <script type="text/javascript"> var str1="Hello "; var str2="world!"; document.write(str1.concat(str2)); </script>
  • 44. fromCharCode() Converts Unicode values to characters syntax: String.fromCharCode(n1, n2, ..., nX) Convert Unicode values to characters: <script type="text/javascript"> document.write(String.fromCharCode(72,69,76,76,79)); </script>
  • 45. indexOf():Returns the position of the first found occurrence of a specified value in a string <script type="text/javascript"> var str="Hello world!"; document.write(str.indexOf("d") + "<br />"); document.write(str.indexOf("WORLD") + "<br />"); document.write(str.indexOf("world")); </script>
  • 46. lastIndexOf():Returns the position of the last found occurrence of a specified value in a string <script type="text/javascript"> var str="Hello world!"; document.write(str.lastIndexOf("d") + "<br />"); document.write(str.lastIndexOf("WORLD") + "<br />"); document.write(str.lastIndexOf(“l")); </script>
  • 47. toLowerCase():Converts a string to lowercase letters <script type="text/javascript"> var str="Hello World!"; document.write(str.toLowerCase()); </script> toUpperCase():Converts a string to uppercase letters <script type="text/javascript"> var str="Hello world!"; document.write(str.toUpperCase()); </script>
  • 48. substr():Extracts the characters from a string, beginning at a specified start position, and through the specified number of character <script type="text/javascript"> var str="Hello world!"; document.write(str.substr(3)+"<br />"); document.write(str.substr(3,4)); </script>
  • 49. replace():Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring <script type="text/javascript"> var str="Visit Microsoft!"; document.write(str.replace("Microsoft", “jntu")); </script>
  • 50. String HTML Wrapper Methods The HTML wrapper methods return the string wrapped inside the appropriate HTML tag. big() Displays a string using a big font blink() Displays a blinking string bold() Displays a string in bold
  • 51. fontcolor() Displays a string using a specified color fontsize() Displays a string using a specified size italics() Displays a string in italic small() Displays a string using a small font strike() Displays a string with a strikethrough link() Displays a string as a hyperlink sub() Displays a string as subscript text sup() Displays a string as superscript text
  • 52. <html> <body> <script type="text/javascript"> var txt = "Hello World!"; document.write("<p>Big: " + txt.big() + "</p>"); document.write("<p>Small: " + txt.small() + "</p>"); document.write("<p>Bold: " + txt.bold() + "</p>"); document.write("<p>Italic: " + txt.italics() + "</p>"); document.write("<p>Strike: " + txt.strike() + "</p>"); document.write("<p>Fontcolor: " + txt.fontcolor("green") + "</p>"); document.write("<p>Fontsize: " + txt.fontsize(6) + "</p>"); document.write("<p>Subscript: " + txt.sub() + "</p>"); document.write("<p>Superscript: " + txt.sup() + "</p>"); document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>"); document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>"); </script> </body> </html>
  • 53. Math Object The Math object allows you to perform mathematical tasks. All properties/methods of Math can be called by using Math as an object, without creating it. Syntax: var x = Math.PI; // Returns PI var y = Math.sqrt(16); // Returns the square root of 16
  • 54. Math Object Methods abs(x):Returns the absolute value of x <script type="text/javascript"> document.write(Math.abs(7.25) + "<br />"); document.write(Math.abs(-7.25) + "<br />"); document.write(Math.abs(null) + "<br />"); document.write(Math.abs("Hello") + "<br />"); document.write(Math.abs(2+3)); </script>
  • 55. ceil(x):Returns x, rounded upwards to the nearest integer <script type="text/javascript"> document.write(Math.ceil(0.60) + "<br />"); document.write(Math.ceil(0.40) + "<br />"); document.write(Math.ceil(5) + "<br />"); document.write(Math.ceil(5.1) + "<br />"); document.write(Math.ceil(-5.1) + "<br />"); document.write(Math.ceil(-5.9)); </script>
  • 56. cos(x):Returns the cosine of x <script type="text/javascript"> document.write(Math.cos(3) + "<br />"); document.write(Math.cos(-3) + "<br />"); document.write(Math.cos(0) + "<br />"); document.write(Math.cos(Math.PI) + "<br />"); document.write(Math.cos(2*Math.PI)); </script>
  • 57. exp(x):Returns the value of E <script type="text/javascript"> document.write(Math.exp(1) + "<br />"); document.write(Math.exp(-1) + "<br />"); document.write(Math.exp(5) + "<br />"); document.write(Math.exp(10) + "<br />"); </script>
  • 58. floor(x):Returns x, rounded downwards to the nearest intege <script type="text/javascript"> document.write(Math.floor(0.60) + "<br />"); document.write(Math.floor(0.40) + "<br />"); document.write(Math.floor(5) + "<br />"); document.write(Math.floor(5.1) + "<br />"); document.write(Math.floor(-5.1) + "<br />"); document.write(Math.floor(-5.9)); </script>
  • 59. log(x):Returns the natural logarithm (base E) of x <script type="text/javascript"> document.write(Math.log(2.7183) + "<br />"); document.write(Math.log(2) + "<br />"); document.write(Math.log(1) + "<br />"); document.write(Math.log(0) + "<br />"); document.write(Math.log(-1)); </script>
  • 60. max(x,y,z,...,n):Returns the number with the highest value min(x,y,z,...,n): Returns the number with the lowest value <script type="text/javascript"> document.write(Math.max(5,10) + "<br />"); document.write(Math.max(0,150,30,20,38) + "<br />"); document.write(Math.max(-5,10) + "<br />"); document.write(Math.max(-5,-10) + "<br />"); document.write(Math.max(1.5,2.5)); </script>
  • 61. Pow(x,y):Returns the value of x to the power of y <script type="text/javascript"> document.write(Math.pow(0,0) + "<br />"); document.write(Math.pow(0,1) + "<br />"); document.write(Math.pow(1,1) + "<br />"); document.write(Math.pow(1,10) + "<br />"); document.write(Math.pow(7,2) + "<br />"); document.write(Math.pow(-7,2) + "<br />"); document.write(Math.pow(2,4)); </script>
  • 62. random():Returns a random number between 0 and 1 <script type="text/javascript"> //return a random number between 0 and 1 document.write(Math.random() + "<br />"); //return a random integer between 0 and 10 document.write(Math.floor(Math.random()*11)); </script>
  • 63. round(x):Rounds x to the nearest integer <script type="text/javascript"> document.write(Math.round(0.60) + "<br />"); document.write(Math.round(0.50) + "<br />"); document.write(Math.round(0.49) + "<br />"); document.write(Math.round(-4.40) + "<br />"); document.write(Math.round(-4.60)); </script>
  • 64. sqrt(x):Returns the square root of x <script type="text/javascript"> document.write(Math.sqrt(0) + "<br />"); document.write(Math.sqrt(1) + "<br />"); document.write(Math.sqrt(9) + "<br />"); document.write(Math.sqrt(0.64) + "<br />"); document.write(Math.sqrt(-9)); </script>
  • 65. Date Object The Date object is used to work with dates and times. Date objects are created with new Date(). There are four ways of instantiating a date: var d = new Date(); var d = new Date(milliseconds); var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
  • 66. Date Object Methods getDate():Returns the day of the month (from 1-31) <script type="text/javascript"> var d = new Date(); document.write(d.getDate()); </script> Return the day of the month from a specific date: <script type="text/javascript"> var d = new Date("July 21, 1983 01:15:00"); document.write(d.getDate()); </script>
  • 67. getDay():Returns the day of the week (from 0-6) <script type="text/javascript"> var d = new Date(); document.write(d.getDay()); </script>
  • 68. Return the name of the weekday (not just a number): <script type="text/javascript"> var d=new Date(); var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; document.write("Today is " + weekday[d.getDay()]); </script>
  • 69. getFullYear():Returns the year (four digits) <script type="text/javascript"> var d = new Date(); document.write(d.getFullYear()); </script> Return the four-digit year from a specific date: <script type="text/javascript"> var d = new Date("July 21, 1983 01:15:00"); document.write("I was born in " + d.getFullYear()); </script>
  • 70. getHours():Returns the hour (from 0-23) <script type="text/javascript"> var d = new Date(); document.write(d.getHours()); </script> Return the hour from a specific date and time: <script type="text/javascript"> var d = new Date("July 21, 1983 01:15:00"); document.write(d.getHours()); </script>
  • 71. getMilliseconds():Returns the milliseconds (from 0-999) <script type="text/javascript"> var d = new Date(); document.write(d.getMilliseconds()); </script> Return the milliseconds from a specific date and time: <script type="text/javascript"> var d = new Date("July 21, 1983 01:15:00"); document.write(d.getMilliseconds()); </script>
  • 72. es():Returns the minutes (from 0-59) h():Returns the month (from 0-11) ds():Returns the seconds (from 0-59) :Returns the number of milliseconds since midnight Jan 1, 1970 oneOffset():Returns the time difference between GMT and local time, in minutes ate():Returns the day of the month, according to universal time (from 1-31) ay():Returns the day of the week, according to universal time (from 0-6)
  • 73. getUTCFullYear():Returns the year, according to universal time (four digits) getUTCHours()Returns the hour, according to universal time (from 0-23) getUTCMilliseconds(): Returns the milliseconds, according to universal time (from 0-999) getUTCMinutes()Returns the minutes, according to universal time (from 0-59) getUTCMonth()Returns the month, according to universal time (from 011) getUTCSeconds()Returns the seconds, according to universal time (from 0-59) setDate()Sets the day of the month (from 1-31) <script type="text/javascript"> var d = new Date(); d.setDate(15); document.write(d); </script>
  • 74. setFullYear()Sets the year (four digits) <script type="text/javascript"> var d = new Date(); d.setFullYear(2020); document.write(d); </script> Set the date to November 3, 1992 <script type="text/javascript"> var d=new Date(); d.setFullYear(1992,10,3); document.write(d); </script>
  • 75. setHours()Sets the hour (from 0-23) Date.setHours(hour,min,sec,millisec) <script type="text/javascript"> var d = new Date(); d.setHours(15); document.write(d); </script> Set the time to 15:35:01: <script type="text/javascript"> var d = new Date(); d.setHours(15,35,1); document.write(d); </script>
  • 76. setMilliseconds()Sets the milliseconds (from 0-999) Set the milliseconds to 192: <script type="text/javascript"> var d = new Date(); d.setMilliseconds(192); document.write(d); </script>
  • 77. setMinutes()Set the minutes (from 0-59) Date.setMinutes(min,sec,millisec) Set the minutes to 01: <script type="text/javascript"> var d = new Date(); d.setMinutes(1); document.write(d); </script> Out Put: Sun Aug 15 2010 19:01:08 GMT+0530 (India Standard Time)
  • 78. setMonth()Sets the month (from 0-11) Date.setMonth(month,day) Set the month to 0 (January): <script type="text/javascript"> var d = new Date(); d.setMonth(0); document.write(d); </script> Set the month to 0 (January) and the day to 20: <script type="text/javascript"> var d = new Date(); d.setMonth(0,20); document.write(d); </script>
  • 79. setSeconds()Sets the seconds (from 0-59) Date.setSeconds(sec,millisec) Set the seconds to 01: <script type="text/javascript"> var d = new Date(); d.setSeconds(1); document.write(d); </script>
  • 80. setTime()Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 Date.setTime(millisec) <script type="text/javascript"> var d = new Date(); d.setTime(77771564221); document.write(d); </script>
  • 81. setUTCDate()Sets the day of the month, according to universal time (from 1-31) setUTCFullYear()Sets the year, according to universal time (four digits) setUTCHours()Sets the hour, according to universal time (from 0-23) setUTCMilliseconds()Sets the milliseconds, according to universal time (from 0- 999) setUTCMinutes()Set the minutes, according to universal time (from 0-59) setUTCMonth()Sets the month, according to universal time (from 0-11) setUTCSeconds()Set the seconds, according to universal time (from 0-59)
  • 82. Opening a New Window To open a new window, you will need to use yet another ready-made JavaScript function. Here is what it looks like: window.open('url to open','window name','attribute1,attribute2') 1.'url to open' This is the web address of the page you wish to appear in the new window. 2. 'window name' You can name your window whatever you like, in case you need to make a reference to the window later. 3. 'attribute1,attribute2' As with alot of other things, you have a choice of attributes you can adjust.
  • 83. Window Attributes Below is a list of the attributes you can use: 1. width=300 Use this to define the width of the new window. 2. height=200 Use this to define the height of the new window. 3. resizable=yes or no Use this to control whether or not you want the user to be able to resize the window. 4. scrollbars=yes or no This lets you decide whether or not to have scrollbars on the window. 5. toolbar=yes or no Whether or not the new window should have the browser navigation bar at the top (The back, foward, stop buttons..etc.). 6. location=yes or no Whether or not you wish to show the location box with the current url (The place to type http://address).
  • 84. 7. directories=yes or no Whether or not the window should show the extra buttons. (what's cool, personal buttons, etc...). 8. status=yes or no Whether or not to show the window status bar at the bottom of the window. 9. menubar=yes or no Whether or not to show the menus at the top of the window (File, Edit, etc...). 10. copyhistory=yes or no Whether or not to copy the old browser window's history list to the new window.
  • 85. <HTML> <HEAD> <TITLE>JavaScript Example 5</TITLE> </HEAD> <BODY> <CENTER> <H1>This is a new window!</H1> </CENTER> <P> <CENTER> <FORM> <input type="button" value="facebook"onclick="window.open('http://www.facebook.com', 'windowname1', 'width=200, height=77'); "> </FORM> </CENTER> </BODY> </HTML>
  • 86. <HTML> <HEAD> <TITLE>JavaScript Example 5</TITLE> </HEAD> <BODY> <CENTER> <H1>This is a new window!</H1> </CENTER> <P> <CENTER> <FORM> <INPUT type="button" value="Close Window" onClick="window.close()"> </FORM> </CENTER> </BODY> </HTML>
  • 87. <html> <head> <script type="text/javascript"> function open_win() { window.open("http://www.w3schools.com","_blank","toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400, height=400"); } </script> </head> <body> <form> <input type="button" value="Open Window" onclick="open_win()"> </form> </body> </html>
  • 89.
  • 90. Login.html <html> <head> <title>Login</title> <script type="text/javascript"> function validate(form){ var userName = form.Username.value; var password = form.Password.value; if (userName.length === 0) { alert("You must enter a username."); return false; } if (password.length === 0) { alert("You must enter a password."); return false; } return true; } </script> </head>
  • 91. <body> <h1>Login Form</h1> <form method="post" action="Process.html" onsubmit="return validate(this);"> Username: <input type="text" name="Username" size="10"><br/> Password: <input type="password" name="Password" size="10"><br/> <input type="submit" value="Submit"> <input type="reset" value="Reset Form"> </p> </form> </body> </html>
  • 92. <html> <head> <title>Login</title> <script type="text/javascript"> function validate(form) { var userName = form.Username.value; var password = form.Password.value; var number=form.PhoneNumber.value; var str=form.Email.value; if (userName.length < 6) { alert("You must enter 6 char a username."); form.Username.focus(); return false; }
  • 93. if (password.length < 6) { alert("You must enter a min 6 char password."); form.Password.focus(); return false; } if(number.length < 10) { alert("enter correct phone number"); form.PhoneNumber.focus(); return false; }
  • 94. var p1,p2,d; p1=str.indexOf('@'); p2=str.indexOf('.'); d=p2-p1; if(p1==0||p2==0||d<=1) { alert("enter correct email id"); form.Email.focus(); return false; } return true; } </script> </head>
  • 95. <body bgcolor="gerren" > <h1>Login Form</h1> <form method="post" action="http://www.gmail.com" onsubmit="return validate(this);"> Username: <input type="text" name="Username" size="10"><br/><br/> Password: <input type="password" name="Password" size="10"><br/> Phone Number: <input type="text" name="PhoneNumber" size="10"><br/> E-mail: <input type="text" name="Email" size="20"><br/> <input type="submit" value="Submit"> <input type="reset" value="Reset Form"> </p> </form> </body> </html>