Unit II Javascript
Unit II Javascript
BASICS OF JAVASCRIPT
Javascript
JavaScript is a simple scripting language invented specifically for use in web
browsers to make websites more dynamic.
JavaScript is a client-side language, which means all the action occurs on the client's
side of things.
JavaScripts are integrated into the browsing environment, which means they can get
information about the browser and HTML page, and modify this information, thus
changing how things are presented on users screen.
Advantages of JavaScript
Less server interaction − You can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
Syntax of JavaScript
<script ...>
JavaScript code
</script>
NMC
JAVASCRIPT
JAVASCRIPT VARIABLES
Example
<script type="text/javascript">
<!--
var name = "Aravind";
var money;
money = 10000;
//-->
</script>
NMC
JAVASCRIPT
Example
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local
NMC
JAVASCRIPT
JAVASCRIPT STRINGS
Example
var answer1 = "It's alright";
var answer2 = "He is called 'Johnny'";
var answer3 = 'He is called "Johnny"';
Special Characters
Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
1.charAt() Method
Return the first character of a string
//charAt()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the last character of the string "HELLO WORLD".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "HELLO WORLD";
var res = str.charAt(str.length-1);
document.getElementById("demo").innerHTML = res;
}
NMC
JAVASCRIPT
</script>
</body>
</html>
2.concat() Method
//concat()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
3. String length
//length()
//Date 26/02/19
<!DOCTYPE html>
<html>
NMC
JAVASCRIPT
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
4. toUpperCase() Method
Convert the string to uppercase letters
//toUppercase()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to convert the string to uppercase letters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello World!";
var res = str.toUpperCase();
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
NMC
JAVASCRIPT
5. toLowerCase() Method
Convert the string to lowercase letters
//toLowerCase()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to convert the string to lowercase letters.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Hello World!";
var res = str.toLowerCase();
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
6. String match()
The match() method searches a string for a match against a regular expression, and
returns the matches, as an Array object.
This method returns null if no match is found.
//str.match()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p>Click the button to perfom a global search for the letters "ain" in a string, and display
the matches.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
NMC
JAVASCRIPT
//String Manipulation
//Date 26/02/19
<script language="JavaScript">
// Define a global search string.
var SearchString = "This is the search string!"
function FindString()
{
// Obtain the value the user wants to find.
var FindValue =
document.getElementById("SearchString").value;
// Perform the search.
var Result = SearchString.indexOf(FindValue);
// Display an appropriate result.
// Check for a blank input first.
if (Result == 0)
{
document.getElementById("Result").innerHTML =
"You must provide an input value!";
}
// Check for a result that doesn't exist next.
else if (Result == -1)
{
document.getElementById("Result").innerHTML =
"The search string doesn't exist.";
}
// Display the location information.
else
{
document.getElementById("Result").innerHTML =
'The search string "' + FindValue +
'" appears at character ' + Result;
}
NMC
JAVASCRIPT
}
</script>
1. Math.abs ()
Math.abs(x) returns the absolute (positive) value of x
//Math.abs()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.abs()</h2>
<p>Math.abs(x) returns the absolute (positive) value of x:</p>
<p id="demo"></p>
NMC
JAVASCRIPT
<script>
document.getElementById("demo").innerHTML = Math.abs(-4.4);
</script>
</body>
</html>
Output
JavaScript Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
4.4
2. Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
//Mat
h.cos()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.cos()</h2>
<p>Math.cos(x) returns the cosin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180);
</script>
</body>
</html>
Output
JavaScript Math.cos()
Math.cos(x) returns the cosin of x (given in radians):
Angle in radians = (angle in degrees) * PI / 180.
The cosine value of 0 degrees is 1
NMC
JAVASCRIPT
3. Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in
radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
//Math.sin()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sin()</h2>
<p>Math.sin(x) returns the sin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>
</body>
</html>
Output
JavaScript Math.sin()
Math.sin(x) returns the sin of x (given in radians):
Angle in radians = (angle in degrees) * PI / 180.
The sine value of 90 degrees is 1
4. Math.round()
Math.round(x) returns the value of x rounded to its nearest integer
NMC
JAVASCRIPT
//Math.round()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.round()</h2>
<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.round(4.4);
</script>
</body>
</html>
Output
JavaScript Math.round()
Math.round(x) returns the value of x rounded to its nearest integer:
5. Math.pow()
//Math.pow()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.pow()</h2>
<p>Math.pow(x,y) returns the value of x to the power of y:</p>
NMC
JAVASCRIPT
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>
</body>
</html>
Output
JavaScript Math.pow()
64
6. Math.sqrt()
//Math.sqrt()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sqrt()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
NMC
JAVASCRIPT
</script>
</body>
</html>
Output
JavaScript Math.sqrt()
7. Math.ceil()
//Math.ceil
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.ceil()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.ceil(4.4);
</script>
</body>
NMC
JAVASCRIPT
</html>
Output
JavaScript Math.ceil()
8. Math.floor()
//Math.floor()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.floor()</h2>
<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest
integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>
</body>
</html>
Output
NMC
JAVASCRIPT
JavaScript Math.floor()
Math.min() and Math.max() can be used to find the lowest or highest value in a list
of arguments
Output
JavaScript Math.min()
NMC
JAVASCRIPT
-200
10. Math.random()
//Math.random()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.random();
</script>
</body>
</html>
Output
JavaScript Math.random()
0.9883295168385227
NMC
JAVASCRIPT
//Math constants
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"<p><b>Math.E:</b> " + Math.E + "</p>" +
"<p><b>Math.PI:</b> " + Math.PI + "</p>" +
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +
"<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
</script>
</body>
</html>
Output
Math.E: 2.718281828459045
Math.PI: 3.141592653589793
NMC
JAVASCRIPT
Math.SQRT2: 1.4142135623730951
Math.SQRT1_2: 0.7071067811865476
Math.LN2: 0.6931471805599453
Math.LN10: 2.302585092994046
Math.LOG2E: 1.4426950408889634
Math.Log10E: 0.4342944819032518
JAVASCRIPT STATEMENTS
NMC
JAVASCRIPT
Flow chart
<html>
NMC
JAVASCRIPT
<body>
<script type="text/javascript">
<!--
var age = 20;
2.if...else statement:
The 'if...else' statement is the next form of control statement that allows JavaScript to
execute statements in a more controlled way.
Syntax
if (expression){
Statement(s) to be executed if expression is true
}
else{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the given
statement(s) in the else block are executed.
//if..else
//Date 26/02/19
<html>
<body>
NMC
JAVASCRIPT
<script type="text/javascript">
<!--
var age = 15;
else{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
else{
NMC
JAVASCRIPT
<html>
<body>
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}
else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>
NMC
JAVASCRIPT
Flow Chart
Syntax
switch (expression)
{
case condition 1: statement(s)
break;
NMC
JAVASCRIPT
default: statement(s)
}
.
//Switch statement
//Date 26/02/19
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
NMC
JAVASCRIPT
Break Statements
Break statements play a major role in switch-case statements.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body> </html>
Output
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...
NMC
JAVASCRIPT
1.For Loop :
Loops through a block of code a specified number of times
Syntax:
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
The condition expression is evaluated. If the value of condition is true, the loop
statements execute. If the value of condition is false, the for loop terminates.
The statements execute.
//for loop
//Date 26/02/19
<html>
<body>
<script language=“javascript”>
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">Visions Developer " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html>
2.While Loop :
Loops through a block of code while a specified condition is true while loop, is used
to run the same block of code while a specified condition is true.
Syntax:
while (var<=endvalue)
{
code to be executed
NMC
JAVASCRIPT
//while loop
//Date 26/02/19
<html>
<body>
<script language=“javascript”>
var i=0
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
3.Do….While Loop
The do...while statement repeats until a specified condition evaluates to false.
Syntax:
do
{
statement
} while
Statement executes once before the condition is checked. If condition returns true,
the statement executes again.
At the end of every execution, the condition is checked. When the condition
returns false, execution stops and control passes to the statement following
do...while.
//Do..while
//Date 26/02/19
<html>
<body>
<script language=“javascript”>
i=0;
do
{
i++;
document.write(i);
NMC
JAVASCRIPT
} while (i<5);
</script>
</body>
</html>
JAVASCRIPT OPERATORS
OPERATOR
-->JavaScript operators are used to assign values, compare values, perform arithmetic
operations, and more..
Types of operators
1. Arithmetic Operators
2. Comparison Operators
3. Logical (or Relational) Operators
4. Assignment Operators
5. Conditional (or ternary) Operators
1. ARITHMETIC OPERATORS
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
NMC
JAVASCRIPT
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
NMC
JAVASCRIPT
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
2. COMPARISON OPERATORS
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
1 = = (Equal)
Checks if the values of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
NMC
JAVASCRIPT
Checks if the value of two operands are equal or not, if the values are not equal,
then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right operand,
if yes, then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the
right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
Example
The following code shows how to use comparison operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
NMC
JAVASCRIPT
document.write(result);
document.write(linebreak);
Set the variables to different values and different operators and then try...
</body>
</html>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
3.LOGICAL OPERATORS
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No Operator and Description
NMC
JAVASCRIPT
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
<p>Set the variables to different values and different operators and then try...</p>
NMC
JAVASCRIPT
</body>
</html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
4.BITWISE OPERATORS
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
Sr.No Operator and Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand two
is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
6 >> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the
number of bits specified by the right operand.
NMC
JAVASCRIPT
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the
left are always zero.
Ex: (A >>> 1) is 1.
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
NMC
JAVASCRIPT
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...
5. ASSIGNMENT OPERATORS
JavaScript supports the following assignment operators −
Sr.No Operator and Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the
left operand.
Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the
left operand.
Ex: C *= A is equivalent to C = C * A
5 /= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.
NMC
JAVASCRIPT
Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=.
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
NMC
JAVASCRIPT
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
6. MISCELLANEOUS OPERATOR
conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
NMC
JAVASCRIPT
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The typeof operator 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.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is
a number, string, or boolean value and returns true or false based on the
evaluation.
Here is a list of the return values for the typeof Operator.
NMC
JAVASCRIPT
Example
The following code shows how to implement typeof operator.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
NMC
JAVASCRIPT
JAVASCRIPT ARRAYS
Syntax:
var array_name = [item1, item2, ...];
//Javascript arrays
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
NMC
JAVASCRIPT
//Sort()
//Date 26/02/19
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>The sort() method sorts an array alphabetically.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body>
</html>
Numeric Sort
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the button to sort the array in ascending order.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
NMC
JAVASCRIPT
</body>
</html>
JAVASCRIPT FUNCTIONS
JavaScript - Functions
JavaScript functions are defined with the function keyword.
Function Declarations
Declared functions are not executed immediately. They are "saved for later use", and will
be executed later, when they are invoked (called upon).
syntax:
function functionName(parameters) {
// code to be executed
}
//Javascript functions
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the
result:</p>
<p id="demo"></p>
NMC
JAVASCRIPT
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
Function Expressions
//Function expression
<!DOCTYPE html>
<html>
<body>
<p>After a function has been stored in a variable,
the variable can be used as a function:</p>
<p id="demo"></p>
<script>
var x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x(4, 3);
</script>
</body>
</html>
NMC
JAVASCRIPT
Output
After a function has been stored in a variable, the variable can be used as a
function:
12
Function Parameters
There is a facility to pass different parameters while calling a function.
These passed parameters can be captured inside the function and any manipulation
can be done over those parameters.
A function can take multiple parameters separated by comma.
//function parameter
<html>
<head>
</script>
</head>
<body>
<form>
NMC
JAVASCRIPT
</form>
</body>
</html>
return Statement
This is required if you want to return a value from a function. This statement
<html>
<head>
var full;
return full;
function secondFunction() {
var result;
NMC
JAVASCRIPT
document.write (result );
</script>
</head>
<body>
<form>
</form>
</body>
</html>
JAVASCRIPT OBJECTS
Javascript objects are containers for named values called properties or methods.
With JavaScript, user can define and create your own objects.
NMC
JAVASCRIPT
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
</script>
</body>
</html>
syntax:
objectName.methodName()
NMC
JAVASCRIPT
//Javascript object
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
Javascript method
NMC
JAVASCRIPT
<!DOCTYPE html>
<html>
<body>
<p>Creating and using an object method.</p>
<p>A method is actually a function definition stored as a property value.</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
NMC
JAVASCRIPT
REGULAR EXPRESSIONS
or simply
1 [^a-zA-Z]
It matches any string not containing any of the characters ranging
from a through z and A through Z.
2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.
3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
NMC
JAVASCRIPT
5 p(hp)*
It matches any string containing a p followed by zero or more instances of
the sequence hp.
RegExp Methods
NMC
JAVASCRIPT
</body>
</html>
RegExp Object
A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace"
functions on text.
Syntax
/pattern/modifiers;
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Output
NMC
JAVASCRIPT
EXCEPTION HANDLING
When a JavaScript statement generates an error, it is said to throw an exception. Instead
of proceeding to the next statement, the JavaScript interpreter checks forexception
handling code. If there is no exception handler, then the program returns from whatever
function threw the exception.
//EXCEPTION HANDLING
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
OUTPUT
NMC
JAVASCRIPT
JAVASCRIPT EVENTS
Event
JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key,
closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element contains a set of events which can trigger JavaScript Code.
1. onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left
button of his mouse. User can put your validation, warning etc., against this event type.
Example
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
NMC
JAVASCRIPT
</html>
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
</body>
</html>
NMC
JAVASCRIPT
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
NMC
JAVASCRIPT
DATA VALIDATION
//data validation
//date 4/2/19
<html>
<head>
<title>Data Validation</title>
</head>
<body>
<form method="post" action="addUser.php"
onSubmit="return Validate()">
<table border="0">
<tr>
<th>Your Name</th>
<td><input type="text" length="24" id="name"/></td>
</tr>
<tr>
<th>Your Age</th>
<td><input type="text" size="3" maxlength="3" id="age"/></td>
</tr>
<tr>
<td><input type="submit" value="submit"/></td>
<td><input type="reset" value="Reset"/></td>
</tr>
</table>
</form>
<script language="javascript">
<!--
function Validate()
{
var valid=false;
var name=document.getElementById("name").value;
var age=document.getElementById("age").value;
NMC
JAVASCRIPT
NMC
JAVASCRIPT
Example
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
NMC
JAVASCRIPT
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
NMC
JAVASCRIPT
<body>
<script
language="javascript">
<!--
prompt("Enter name")
confirm("Are you sure?")
alert("warning")
//-->
</script>
</body>
</html>
STATUS BAR
Status Bar
<html>
<head>
<script language="javascript">
<!--
function Init()
{
self.status="Chris's Message";
}
//-->
</script>
</head>
<body onLoad="Init()">
<h1>And the Status Bar Says...</h1>
</body>
</html>
WRITING TO A DIFFERENT FRAME
NMC
JAVASCRIPT
</html>
NMC
JAVASCRIPT
Rollover buttons
//Rollover image.html
//date 11/02/19
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type="text/javascript">
<!--
if(document.images){
var image1 = new Image(); // Preload an image
image1.src = "/images/html.gif";
var image2 = new Image(); // Preload second image
image2.src = "/images/http.gif";
}
//-->
NMC
JAVASCRIPT
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
MOVING IMAGES
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in
20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload =init;
NMC
JAVASCRIPT
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="D:\Tulips11.jpg" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>
TEXT-ONLY MENU SYSTEM
Text only menu system
<!DOCTYPE html>
<html>
<body>
<div style="background:yellow;border:1px solid #cccccc;padding: 10px;"
contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!</p>
<menu type="context" id="mymenu">
<menuitem label="Refresh" onclick="window.location.reload();"
icon="ico_reload.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter" icon="ico_twitter.png"
onclick="window.open('//twitter.com/intent/tweet?text=' + window.location.href);">
</menuitem>
<menuitem label="Facebook" icon="ico_facebook.png"
onclick="window.open('//facebook.com/sharer/sharer.php?u=' +
window.location.href);">
</menuitem>
</menu>
<menuitem label="Email This Page" onclick="window.location='mailto:?
body='+window.location.href;"></menuitem>
</menu>
FLOATING LOGOS
NMC
JAVASCRIPT
Floating logos
With the help of this script you can put up your logo on your website in such a way
that it floats on the page in any particular location that can be set.
//FLOATING LOGOS
<html>
<head>
<script language=javascript src="logo.js">
</script>
</head>
<body onLoad=Init()>
<div id="lay()" style="visibility: visible;
position: absolute; width:95%">
<!--Your Content Here-->
</div>
<div id="lay10"
style="visibility: visible;
position: absolute;
font-size: 20pt;
background: aquamarine;
color: purple;
text-align: center;
left: 5px;
top: 5px;
width: 256px;
height: 64px;">
<p>LOGO</p>
</div>
function init()
{
setup();
positionLogo();
}
</body>
</html>
FORM VALIDATION
NMC
JAVASCRIPT
//FORM VALIDATION
//DATE 4/2/19
<html>
<head>
<script language="javascript">
function validate()
{
var method=document.forms[0].method;
var action=document.forms[0].action;
var value=document.forms[0].elements[0].value;
if(value!="Mary")
{
document.forms[0].reset();
}
else
{
alert("Hi Mary!!");
}
}
</script>
</head>
<body>
<form method="post">
<input type="text" id="user" size="32"/>
<input type="submit" value="press me!"
onClick="validate()"/>
</form>
</body>
</html>
NMC