Professional Documents
Culture Documents
Vizu.chowdary@gmail.com JSCRIPT - 1
What CSS does?
Looks and formatting the document written in the mark-up language.(it impacts the document)
How the CSS know the para is located at somewhere? So there should be a mean by which the CSS should traverse to
the para.
So CSS should have an access to dig in to this para <p>
OUTPUT:
Vizu.chowdary@gmail.com JSCRIPT - 2
CSS it is working on the document elements (or) it is traversing to the DOM.
CSS will impact on para <p>
HTML
HEAD BODY
Whatever html document that we are specifying, somewhere its model has been defined and gets loaded.
DOM STARTSDOCUMENT
HTML
HEAD BODY
CSS checks, the role of the css is to dig into the DOM and whatever task has been asked to css loads.
DOM is created at BROWSER level.
Vizu.chowdary@gmail.com JSCRIPT - 3
Basic object of DOM:
- Screen (which provides height, width to us)
- Window (e.g., alert)
- Document: The web page displayed in the browser window is represented by the document object.
----------------------------------------------------------WIDTH----------------------------------------------------------
--------------------------------------HEIGHT--------------------------------------------------
Vizu.chowdary@gmail.com JSCRIPT - 4
IN OUR PROGRAM CAN WE SEE THE DOM?
Yes, it’s possible. Using Mozilla Fire fox.
If you don’t have FIREBUG add-on in fire fox. Install it.
Press F12
Click on DOM
Vizu.chowdary@gmail.com JSCRIPT - 5
WINDOW (WITH THIS WE HAVE SO MANY OBJECTS, MAINLY WE WILL BE CONSIDERING SCREEN)
We can see the document here (expand this, we can find lot of objects)
Vizu.chowdary@gmail.com JSCRIPT - 6
Here we are looking something called as CHILDREN (EXPAND THIS)
Vizu.chowdary@gmail.com JSCRIPT - 7
Only one CHILDREN is available (expand this)
Vizu.chowdary@gmail.com JSCRIPT - 8
First Child is head
I am not looking for this. I am looking for CHILDREN.
Click here on HTML COLLECTION
Vizu.chowdary@gmail.com JSCRIPT - 9
Here we can see
WINDOW (we can click on this)
Within Window we went to DOCUMENT (we can click on this)
Within Document we went to CHILDREN (we can click on this)
0 CHILDREN (WITH IN THIS CHILDREN) (we can click on this)
Vizu.chowdary@gmail.com JSCRIPT - 10
So it is going to the 1st CHILDREN
Whenever HTML page gets loaded, DOM objects get created at browser level.
Browser is also an application. Browser is also a software. It has its own task.
Vizu.chowdary@gmail.com JSCRIPT - 11
DOM TREE:
- Each HTML element in a web page becomes a node in the DOM tree.
- HTML tags are known as elements and the actual content between the start tag and end tag are known as a text
node.
- The superordinate element are known as parent objects.
E.g.
<li> parent node is <ol>
<ol> parent node is <body>
- Subordinate element are known as children.
- Elements of the same rank are known as siblings
Vizu.chowdary@gmail.com JSCRIPT - 12
DOM TREE
Vizu.chowdary@gmail.com JSCRIPT - 13
INBUILT METHODS
document.getElementById()
This will be used extensively by us.
Vizu.chowdary@gmail.com JSCRIPT - 14
Another way is
getElementByTagName()
Whatever tag name we provided like para <p>, <body>
E.G.
37-38-15
DOM MANIPULATION:
You cannot only access the DOM in ready-only mode, but also change properties, move existing objects, add new
objects, and even delete objects.
- InnerHTML (to add, modify content): this is like text node.
Adding Elements
- appendChild();
- cloneNode();
- removeChild();
Java Script
HTML
Java Script is more on Mathematical operations
Meant for
designing Contains / more into PROGRAMMING DECISION
Vizu.chowdary@gmail.com JSCRIPT - 15
JAVASCRIPT VS DOM MANIPULATION
OUTPUT:
Click on this
Vizu.chowdary@gmail.com JSCRIPT - 16
Vizu.chowdary@gmail.com JSCRIPT - 17
DEBUG THE MISTAKE IN JAVASCRIPT
Vizu.chowdary@gmail.com JSCRIPT - 18
I can see 1 error.
Vizu.chowdary@gmail.com JSCRIPT - 19
Blink yellow color once and disappear.
Vizu.chowdary@gmail.com JSCRIPT - 20
Try to download (like fire bug)
Developer tools for Google chrome.
==================================================================================================
Click on ADD
Vizu.chowdary@gmail.com JSCRIPT - 21
DIFFERENCE BETWEEN SCRIPTING & LANGUAGES?
SCRIPTING LANGUAGES
1) LIGHT WEIGHT PROGRAMMING. 1) HEAVY WEIGHT PROGRAMMING.
E.G. E.G.
A) DOCUMENT.WRITE("BVK"); <- JAVA SCRIPT INCLUDE <STUDIO.H>
B) ECHO "BVK" <------------------------- SHELL MAIN( )
C) MSGBOX ("BVK") <--------------- IN VB SCRIPT {
D) PRINT("WELCOME"); <---------------- PERL }
2) EASY TO UNDERSTAND 2) COMPLEX TO UNDERSTAND
3) EASY TO IMPLEMENT 3) TROUBLE TO IMPLEMENT.
4) NO HEADER FILES REQUIRED 4) HEADER FILES ARE MANDATORY
5) NO SPECIAL LIBRARIES 5) REQUIRED SPECIAL LIBRARIES
6) NO SPECIAL COMPILERS 6) EVERY LANGUAGE, THEY REQUIRE THEIR OWN COMPILERS
7) MAXIMUM INTERPRETER BASED 7) MAXIMUM COMPILER BASED.
8) MOST TYPED PROGRAMMING (GLOBAL VARIABLE 8) STRICTLY TYPED PROGRAMMING (VARIABLE DECLARATION
DECLARATION) REQUIRED SEMICOLON, COMMA, QUOTATION MANDATORY)
9) CLIENT-SIDE VALIDATAION PURPOSE 9) VERIFICATION & VALIDATION BOTH.
10) POOR IN GRAPHICS IMPLEMNETATION 10) RICH IN GRAPHICS IMPLEMENTATION.
E.G. JAVA SCRIPT, VB SCRIPT, PERL SCRIPT ETC., E.G. C, C++, JAVA, COBOL, FORTRAN.
Vizu.chowdary@gmail.com JSCRIPT - 22
INTRODUCTION TO JAVA SCRIPT?
TO MAKE HTML DYNAMIC WE USE JAVASCRIPT PROGRAMMING.
THERE IS NO RELATIONSHIP BETWEEN JAVA & JAVASCRIPT, THEY ARE STANDALONE PROGRAMMING
LANGUAGES.
JAVASCRIPT IS NOT EXECUTABLE FILE AS HTML, IT SHOULD BE INCLUDED IN HTML FILE. (AS CSS)
IT IS FIRST WEB SCRIPTING LANGUAGE. IT IS CLIENT SIDE SCRIPTING LANGUAGE DEVELOPED BY "BRENDAN
RICH" IN NETSCAPE CORPORATION AT 1995. IT IS SUPPORTING ALL MAJOR MODERN BROWSERS LIKE GOOGLE
CHROME, MOZILLA FIREFOX, OPERA, SAFARI, I.E,
NETSCAPE CORPORATION CAME OUT WITH A CLIENT SIDE SCRIPTING I.E. KNOWN AS LIVESCRIPT. IT IS THE FIRST
WEBSCRIPTING LANGUAGE.
MICROSOFT CORPORATION JAVASCRIPT VERSION IS JSCRIPT. IT WAS FIRST INTRODUCED WITH I.E. VERSION 3.
(IT IS INITIALLY LIVESCRIPT. LATER RENAMED AS JAVASCRIPT).
NATURE OF JAVASCRIPT?
IT IS OBJECT BASED PROGRAMMING LANGUAGE.
IT IS BASED ON OBJECT ORIENTED PROGRAMMING CONCEPT.
ITS SYNTAX IS SIMILAR TO C, C++ AND JAVA. IT IS EASY & SIMPLE TO IMPLEMENT.
Important Points:
Java Script is CASE SENSITIVE.
Vizu.chowdary@gmail.com JSCRIPT - 23
WHAT IS JAVASCRIPT?
JAVA SCRIPT IS SATISFYING THE FOLLOWING LIST OF POINTS.
IT IS USED TO VALIDATE DATA.
IT IS USED TO CREATE COOKIES
1) IT IS BASICALLY LIVESCRIPT.
2) IT IS PURE CLIENT-SIDE PROGRAMMING TOOL.
3) IT CAN INTEGRATE WITH HTML TAGS.
4) IT IS LIGHTWEIGHT SCRIPTING.
5) IT IS INTERPRETED PROGRAMMING.
6) IT IS DESINERS PROGRAMMING TOOL.
7) IT CAN REACT TO EVENTS.
8) IT CAN READ & WRITE HTML ELEMENTS.
9) IT CAN INTEGRATE WITH ANY SERVER-SIDE PROGRAMMING.
10) OPEN SOURCE AND CROSS PLATFORM.
11) IT CREATES & READ THE EVENTS.
12) JAVASCRIPT CAN INTEGRATE WITH HTML & CSS CALLED DHTML.
CLIENT-SIDE JAVASCRIPT:
The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would
be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that
the user explicitly or implicitly initiates.
ADVANTAGES OF JAVASCRIPT:
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features:
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.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into
otherwise static HTML pages.
Vizu.chowdary@gmail.com JSCRIPT - 24
JAVASCRIPT SYNTAX:
A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web
page.
You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way
to keep it within the <head> tags.
The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So
simple syntax of your JavaScript will be as follows
<SCRIPT>......................</SCRIPT>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
We added an optional HTML comment that surrounds our Javascript code. This is to save our code from a browser that
does not support Javascript. The comment ends with a "//-->". Here "//" signifies a comment in Javascript, so we add
that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code.
Next, we call a function document.write which writes a string into our HTML document. This function can be used to
write text, HTML, or both. So above code will display following result:
Vizu.chowdary@gmail.com JSCRIPT - 25
Semicolons are Optional:
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java.
JavaScript, however, allows you to omit this semicolon if your statements are each placed on a separate line. For
example, the following code could be written without semicolons
<script language="javascript" type="text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, the semicolons are required:
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of letters.
So identifiers Time, TIme and TIME will have different meanings in JavaScript.
NOTE: Care should be taken while writing your variable and function names in JavaScript.
E.g.
Java Script is basically case-sensitive programming. A function named "Myfunction" is not equal to "MyFunction" &a
variable named "MyVar" is not the same as "Myvar".
Vizu.chowdary@gmail.com JSCRIPT - 26
******************************NOTES: ******************************
SCRIPT:
Generally script or <script > tag contains following 2 essential attributes.
1) Language
2) Type.
1) SINGLE LINE COMMENTS: These comments are restricted to within the line.
The notation is // (Double Forward Slash)
2) MULTI LINE COMMENTS: These comments are related to multiple java statements are multiple lines.
The notation is /* */
E.G.
/*
document.write("HELLO");
document.write("<h1> This is a header</h1>")
*/
Vizu.chowdary@gmail.com JSCRIPT - 27
<SCRIPT> TAG DESCRIPTION:
It is a tag which indicates script interpreter required to escalate lines between
<script>
------------------
------------------
</script> these tags.
If you did not mention <script> tag, Browser interprets are printing as normal strings. These strings displayed on
the webpage.
<html>
<head>
<script type = "text/javascript">
document.write("it is 'LIVE' script");
document.write("<br/>");
document.write("It is javascript from Netscape");
</script>
</head>
</html>
WORKING WITH SINGLE & DOUBLE QUOTES IN JAVASCRIPT:
Single & double quotes to produce the same results.
Will make you a clear picture on Single & double quotes.
Vizu.chowdary@gmail.com JSCRIPT - 28
There is an escape character \ before. The java script will ignore. With \ I can display the double quotes
OUTPUT:
E.g. (1)
<script>
var txt = "we are the so-called 'GOOD' from the SOUTH.";
document.write(txt);
</script>
E.g. (2)
<script>
var txt = "we are the so-called "GOOD" from the SOUTH.";
document.write(txt);
</script>
Output: BLANK.
E.g. (3)
<script>
var txt = "we are the so-called \"GOOD\" from the SOUTH.";
document.write(txt);
</script>
Vizu.chowdary@gmail.com JSCRIPT - 29
CODE OUTPUT
\' Single Quote
\" Double Quote
\\ Back Slash
\n New line
\r Carriage Return
\t Tab
\b Backspace
\f Form feed
We can break up a code line with in a text string with a back slash.
<script>
document.write("HELLO \ WORLD!");
</script>
There is no difference between the above statements. Here, the window object is highest level object. It contain other
objects & their methods.
Document is object content inside the window objects. WRITE is a method of document object.
In that situation, window object is not necessary.
E.g.
<script>
document.write("HelloWorld!");
document.write("<br>");
window.document.write("BVK");
</script>
E.g.
<script>
document.write("Hello World!");
document.write("BVK");
</script>
Vizu.chowdary@gmail.com JSCRIPT - 30
ENABLING JAVASCRIPT IN BROWSERS
JavaScript in Firefox:
Here are simple steps to turn on or turn off JavaScript in your Firefox:
1) Follow Tools-> Options
from the menu
2) Select Content option from the dialog box
3) Select Enable JavaScript checkbox
4) Finally click OK and come out
To disable JavaScript support in your Firefox, you should not select Enable JavaScript checkbox.
JavaScript in Opera:
Here are simple steps to turn on or turn off JavaScript in your Opera:
1) Follow Tools-> Preferences
from the menu
2) Select Advanced option from the dialog box
3) Select Content from the listed items
4) Select Enable JavaScript checkbox
5) Finally click OK and come out
To disable JavaScript support in your Opera, you should not select Enable JavaScript checkbox.
Vizu.chowdary@gmail.com JSCRIPT - 31
JAVASCRIPT PLACEMENT IN HTML FILE
There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most
preferred ways to include JavaScript in your HTML file.
In the following section we will see how we can put JavaScript in different ways:
If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in
the head as follows:
OUTPUT:
Vizu.chowdary@gmail.com JSCRIPT - 32
JavaScript in <body>...</body> section:
If you need a script to run as the page loads so that the script generates content in the page, the script goes in the
<body> portion of the document. In this case you would not have any function defined using JavaScript:
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
You can put your JavaScript code in <head> and <body> section altogether as follows:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 33
JavaScript in External File:
As you begin to work more extensively with JavaScript, you will likely find that there are cases where you are
reusing identical JavaScript code on multiple pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a
mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code using script tag
and its src attribute:
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write your all JavaScript source code in a simple text file with
extension ".js" and then include that file as shown above.
For example, you can keep following content in filename.js file and then you can use sayHello function in your HTML file
after including filename.js file:
function sayHello() {
alert("Hello World")
}
To use external script, point to .js file, we are using “SRC” attribute.
<html>
<head>
<script type = “text/javascript” src = “myscript.js”> </script>
</head>
<body>
</body>
</html>
Save file with .html extension or .html extension
Vizu.chowdary@gmail.com JSCRIPT - 34
PREPARE JAVA SCRIPT (SAVE AS .JS FILE)
function show_alert()
{
alert("HI");
}
function show_confirm()
{
confirm("HELLOW");
}
JavaScript DataTypes:
One of the most fundamental characteristics of a programming language is the set of data types it supports.
These are the type of values that can be represented and manipulated in a programming language.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.
In addition to these primitive data types, JavaScript supports a composite data type known as object. We will
see an object detail in a separate chapter.
Note: Java does not make a distinction between integer values and floating-point values. All numbers in
JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-
point format defined by the IEEE 754 standard.
Vizu.chowdary@gmail.com JSCRIPT - 35
Declaring variables:
OUTPUT:
Vizu.chowdary@gmail.com JSCRIPT - 36
I am over writing this program.
What is the data type of this variable?
OUTPUT:
Java Script takes the type of variable dynamically. We need not worry of declaring a data type for a variable.
Type of variable
Vizu.chowdary@gmail.com JSCRIPT - 37
HOW JAVA SCRIPT IS INTERPRETED?
Done at the Browser. Browser has to understand HTML, Jscript.
Vizu.chowdary@gmail.com JSCRIPT - 38
JavaScript Variables:
RULES:
Every Variable should starts with an Alphabet or Underscore.
Variable should not contain un-necessary special characters.
Variable should not contain embedded periods. (dots).
Variable are case sensitive.
Count, count and COUNT are 3 different variables.
Variable should be reasonable length.
Variables declared with ‘var’ keyword.
EXAMPLE: Var x;
Var carname;
These are the empty variables. If you want, you can assign values to these variables.
Var x = 5;
Var name = “BVK”.
Note: We are using + operator to concatenate string and number all together. JavaScript does not mind in
adding numbers into strings.
Vizu.chowdary@gmail.com JSCRIPT - 39
Write a script, to read 2 values, to display sum and difference.
<html>
<head>
<title> VARIABLES </title>
</head>
<script type = "text/javascript">
var a = prompt("Enter any value:", "10");
var b = prompt("Enter any value:", "20");
var c = a + b;
var d = a - b;
document.write("the value of a is:" +a);
document.write("<br>");
document.write("the value of b is:" +b);
document.write("<br>");
document.write("the value of c is:" +c);
document.write("<br>");
document.write("the value of d is:" +d);
</script>
<body> </body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 40
JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in mind.
You should not use any of the JavaScript reserved keyword as variable name. For
example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the
underscore character. For example, 123test is an invalid variable name but_123test is a valid one.
JavaScript variable names are case sensitive. For example, Name and name are two different variables.
JavaScript Reserved Words:
The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions,
methods, loop labels, or any object names.
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
Vizu.chowdary@gmail.com JSCRIPT - 41
PROGRAM:
HTML FILE
JSCRIPT FILE
Vizu.chowdary@gmail.com JSCRIPT - 42
In any browser, title bar, tool bar, address bar is called as WINDOW OBJECT.
Vizu.chowdary@gmail.com JSCRIPT - 43
PROGRAM:
Within the document I can use html tag <br> <h1> </h1>
EXECUTE in FIREFOX
Vizu.chowdary@gmail.com JSCRIPT - 44
Here we are not getting JSCRIT TEXT.
Use this
Vizu.chowdary@gmail.com JSCRIPT - 45
Wontedly, I made an error
EXECUTE IN CHROME.
Press F12
LINE 9
Click on it
Vizu.chowdary@gmail.com JSCRIPT - 46
This is the screen which I get after clicking
CLICK ON THIS
Vizu.chowdary@gmail.com JSCRIPT - 47
A CONSOLE FOR DISPLAYING ERRORS/LOGS
A DEBUGGER
BROWSER KEYBOARD
FIREFOX F12
MICROSOFT IE F12
CHROME F12
SAFARI CTRL+ALT+I
OPERA CTRL+ALT+I
Vizu.chowdary@gmail.com JSCRIPT - 48
VARIABLE DECLARATIONS
Variable names must begin with a letter
Variable names can also begin with $ and _
Variable names are case sensitive.
Reserved words (like JavaScript keywords) cannot be used as variable names.
Vizu.chowdary@gmail.com JSCRIPT - 49
PROGRAM - 4:
Output is 2.4.
No need to specify the data type. Dynamically it takes. This is one of advantage.
DATA TYPES
In JavaScript there are 5 different data types that can contain values:
o string
o number
o Boolean
o Object (will discuss later).
o Function (will discuss later).
JavaScript has Dynamic Types
BOOLEAN TEXT
Vizu.chowdary@gmail.com JSCRIPT - 50
JAVASCRIPT OPERATORS
WHAT IS AN OPERATOR?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is
called operator. JavaScript language supports following type of operators.
Arithmetic Operators
Comparison Operators / Assignment Operators
Logical (or Relational) Operators
Conditional (or ternary) Operators
Let’s have a look on all operators one by one.
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Vizu.chowdary@gmail.com JSCRIPT - 51
<html>
<body>
<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;
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);
Vizu.chowdary@gmail.com JSCRIPT - 52
//-->
</script>
Result
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
Vizu.chowdary@gmail.com JSCRIPT - 53
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
Result
var b = 20;
var linebreak = "<br />"; (a == b) => false
(a < b) => true
document.write("(a == b) => "); (a > b) => false
result = (a == b);
(a != b) => true
document.write(result);
(a >= b) => false
document.write(linebreak);
(a <= b) => true
document.write("(a < b) => ");
result = (a < b); Set the variables to different values and different
document.write(result); operators and then try...
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 54
The Logical Operators:
There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
&& Called Logical AND operator. If both the operands are non (A && B) is true.
zero then then condition becomes true.
|| Called Logical OR Operator. If any of the two operands are (A || B) is true.
non zero then then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is false.
state of its operand. If a condition is true then Logical NOT
operator will make false.
<html>
<body>
Result:
<script type="text/javascript">
<!-- (a && b) => false
var a = true; (a || b) => true
var b = false; !(a && b) => true
var linebreak = "<br />";
document.write("(a && b) => "); Set the variables to different values and
result = (a && b); different operators and then try...
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 55
The Bitwise Operators:
There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
Operator Description Example
& Called Bitwise AND operator. It performs a Boolean AND operation on each (A & B) is 2 .
bit of its integer arguments.
| Called Bitwise OR Operator. It performs a Boolean OR operation on each bit (A | B) is 3.
of its integer arguments.
^ Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation (A ^ B) is 1.
on each bit of its integer arguments. Exclusive OR means that either operand
one is true or operand two is true, but not both.
~ Called Bitwise NOT Operator. It is a is a unary operator and operates by (~B) is -4 .
reversing all bits in the operand.
<< Called Bitwise Shift Left Operator. It moves all bits in its first operand to the (A << 1) is 4.
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 by 2, shifting two positions is equivalent to multiplying by 4, etc.
>> Called Bitwise Shift Right with Sign Operator. It moves all bits in its first (A >> 1) is 1.
operand to the right by the number of places specified in the second
operand. The bits filled in on the left depend on the sign bit of the original
operand, in order to preserve the sign of the result. If the first operand is
positive, the result has zeros placed in the high bits; if the first operand is
negative, the result has ones placed in the high bits. Shifting a value right one
place is equivalent to dividing by 2 (discarding the remainder), shifting right
two places is equivalent to integer division by 4, and so on.
>>> Called Bitwise Shift Right with Zero Operator. This operator is just like the >> (A >>> 1) is 1.
operator, except that the bits shifted in on the left are always zero,
Vizu.chowdary@gmail.com JSCRIPT - 56
<html>
<body>
<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 57
The Assignment Operators:
There are following assignment operators supported by JavaScript language:
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will assigne value of A + B
operands to left side operand into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C = C + A
left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C - A
operand from the left operand and assign the result to left
operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C * A
operand with the left operand and assign the result to left
operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalent to C = C / A
with the right operand and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using C %= A is equivalent to C = C % A
two operands and assign the result to left operand
Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.
Vizu.chowdary@gmail.com JSCRIPT - 58
<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 59
Miscellaneous Operator
The Conditional Operator (? :)
There is an operator called conditional operator. This first evaluates an expression for a true or false value and
then execute one of the two given statements depending upon the result of the evaluation. The conditioanl
operator has this syntax:
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Result
Vizu.chowdary@gmail.com JSCRIPT - 60
The 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.
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 the list of return values for the typeof Operator :
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
<html> RESULT
<body>
Result => B is String
<script type="text/javascript"> Result => A is Numeric
<!--
var a = 10; Set the variables to different values and
var b = "String"; different operators and then try...
var linebreak = "<br />";
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 61
STRING CONCATENATION (+)
There + operator used on strings. To add 2 strings variables this operator is required.
Eg.
Str1 = “NIL”;
Str2 = “PIN2”;
Str3 = Str1 + str2;
Program
<html>
<body>
<script type = "text/javascript">
var x;
x = 1 + 5;
document.write(x);
document.write("<br>");
x = 1 + "5";
document.write(x);
document.write("<br>");
x = "1" + "5";
document.write(x);
document.write("<br>");
</script>
</body>
</html>
Result
6
15
15
Vizu.chowdary@gmail.com JSCRIPT - 62
• IF
• SWITCH
• WHILE
• DO..WHILE
• FOR
Vizu.chowdary@gmail.com JSCRIPT - 63
JAVASCRIPT IF………..ELSE
While writing a program, there may be a situation when you need to adopt one path out of the given two
paths. So you need to make use of conditional statements that allow your program to make correct decisions
and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different
conditions. Here we will explain if..else statement.
JavaScript supports following forms of if..else statement:
if statement
if...else statement
if...else if... statement.
if statement:
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute
statements conditionally.
Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) are executed.
If expression is false then no statement would be not executed. Most of the times you will use comparison
operators while making decisions.
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
Vizu.chowdary@gmail.com JSCRIPT - 64
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
Result
if...else statement:
The if...else statement is the next form of control statement that allows JavaScript to execute statements in
more controlled way.
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
Vizu.chowdary@gmail.com JSCRIPT - 65
<html>
<body>
<script type="text/javascript">
<!--
var age = 15;
Result
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
}
Vizu.chowdary@gmail.com JSCRIPT - 66
<html>
<body>
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>
Result
Maths Book
Vizu.chowdary@gmail.com JSCRIPT - 67
JAVASCRIPT SWITCH CASE
You can use multiple if...else if statements, to perform a multiway branch. However, this is not always the
best solution, especially when all of the branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does
so more efficiently than repeated if...else if statements.
Syntax:
The basic syntax of the switch statement is to give an expression to evaluate and several different statements
to execute based on the value of the expression. The interpreter checks eachcase against the value of the
expression until a match is found. If nothing matches, a default condition will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate to the interpreter the end of that particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Vizu.chowdary@gmail.com JSCRIPT - 68
<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;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
RESULT
Vizu.chowdary@gmail.com JSCRIPT - 69
Consider a case if you do not use break statement:
<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>
Result
Vizu.chowdary@gmail.com JSCRIPT - 70
JAVASCRIPT WHILE LOOP
While writing a program, there may be a situation when you need to perform some action over and over
again. In such situation you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to help you on all steps of programming.
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.
Syntax:
WHILE (EXPRESSION){
STATEMENT(S) TO BE EXECUTED IF EXPRESSION IS TRUE
}
The purpose of a while loop is to execute a statement or code block repeatedly as long asexpression is true.
Once expression becomes false, the loop will be exited.
<html>
<body> Starting LoopCurrent Count : 0
Current Count : 1
<script type="text/javascript"> Current Count : 2
<!--
Current Count : 3
var count = 0;
Current Count : 4
document.write("Starting Loop");
Current Count : 5
while (count < 10){
Current Count : 6
document.write("Current Count : " + count + "<br />");
count++; Current Count : 7
} Current Count : 8
document.write("Loop stopped!"); Current Count : 9
//--> Loop stopped!
</script>
Set the variable to different value and then try...
<p>Set the variable to different value and then try...</p>
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 71
The do...while Loop:
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop.
This means that the loop will always be executed at least once, even if the condition is false.
do{
Statement(s) to be executed;
} while (expression);
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
Result
Starting Loop
Current Count : 0
Loop stopped!
Vizu.chowdary@gmail.com JSCRIPT - 72
JAVASCRIPT FOR LOOP
Vizu.chowdary@gmail.com JSCRIPT - 73
JAVASCRIPT FOR……IN LOOP
There is one more loop supported by JavaScript. It is called for...in loop. This loop is used to loop through an
object's properties.
Because we have not discussed Objects yet, so you may not feel comfortable with this loop. But once you will
have understanding on JavaScript objects then you will find this loop very useful.
In each iteration one property from object is assigned to variablename and this loop continues till all the
properties of the object are exhausted.
Navigator Object Properties
webkitPersistentStorage
<html> webkitTemporaryStorage
<body> geolocation
doNotTrack
OUTPUT onLine
<script type="text/javascript">
languages
<!-- language
var aProperty; userAgent
document.write("Navigator Object Properties<br /> "); product
for (aProperty in navigator) platform
{ appVersion
appName
document.write(aProperty);
appCodeName
document.write("<br />"); hardwareConcurrency
} maxTouchPoints
document.write("Exiting from the loop!"); vendorSub
//--> vendor
</script> productSub
cookieEnabled
mimeTypes
<p>Set the variable to different object and then try...</p> plugins
</body> javaEnabled
</html> getStorageUpdates
vibrate
getBattery
webkitGetGamepads
getGamepads
webkitGetUserMedia
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Vizu.chowdary@gmail.com JSCRIPT - 74
JAVASCRIPT LOOP CONTROL
JavaScript provides you full control to handle your loops and switch statement. There may be a situation when
you need to come out of a loop without reaching at its bottom. There may also be a situation when you want
to skip a part of your code block and want to start next iteration of the look.
To handle all such situations, JavaScript provides break and continue statements. These statements are used
to immediately come out of any loop or to start the next iteration of any loop respectively.
The break Statement:
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early,
breaking out of the enclosing curly braces.
Example:
This example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early
once x reaches 5 and reaches to document.write(..) statement just below to closing curly brace:
We already have seen the usage of break statement inside a switch statement.
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
RESULT
Entering the loop
2
3
4
5
Exiting the loop!
Vizu.chowdary@gmail.com JSCRIPT - 75
The continue Statement:
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip
remaining code block.
When a continue statement is encountered, program flow will move to the loop check expression
immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.
Example:
This example illustrates the use of a continue statement with a while loop. Notice how thecontinue statement
is used to skip printing when the index held in variable x reaches 5:
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Vizu.chowdary@gmail.com JSCRIPT - 76
Set the variable to different value and then try...
<html>
<body>
Entering the loop!
<script type="text/javascript"> Outerloop: 0
<!-- Innerloop: 0
document.write("Entering the loop!<br /> "); Innerloop: 1
outerloop: // This is the label name Innerloop: 2
for (var i = 0; i < 5; i++)
Innerloop: 3
{
Outerloop: 1
document.write("Outerloop: " + i + "<br />");
Innerloop: 0
innerloop:
Innerloop: 1
for (var j = 0; j < 5; j++)
{ Innerloop: 2
if (j > 3 ) break ; // Quit the innermost loop Innerloop: 3
if (i == 2) break innerloop; // Do the same thing Outerloop: 2
if (i == 4) break outerloop; // Quit the outer loop Outerloop: 3
document.write("Innerloop: " + j + " <br />"); Innerloop: 0
} Innerloop: 1
} Innerloop: 2
document.write("Exiting the loop!<br /> "); Innerloop: 3
//--> Outerloop: 4
</script> Exiting the loop!
</body>
</html>
Vizu.chowdary@gmail.com JSCRIPT - 77
<html>
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
RESULT
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!
Vizu.chowdary@gmail.com JSCRIPT - 78
Vizu.chowdary@gmail.com JSCRIPT - 79
EVENTS
WHAT IS AN EVENT?
Whatever the action that perform by the user.
Event can be, when you are specifying something on the input field user name, that can be a event.
Whatever task done by end user can be called as EVENT.
E.g.
Click on button is an event.
(OR)
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or browser
manipulates a page.
When the page loads, that is an event. When the user clicks a button, that click, too, is an event. Another
example of events are like pressing any key, closing window, resizing 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 to occur.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element have a certain set of
events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see few
examples to understand a relation between Event and JavaScript:
onclick Event Type:
This is the most frequently used event type which occurs when a user clicks mouse left button. You can put
your validation, warning etc against this event type.
Vizu.chowdary@gmail.com JSCRIPT - 80
PROGRAM:
EVENT: onclick
Onclick is an event (inline javascript code). ONCLICK is in built event. Specified by html & JSCRIPT.
------------------------------------------:OUTPUT: ------------------------------------------
Vizu.chowdary@gmail.com JSCRIPT - 81
PROGRAM :
EVENT: onmouseover
OUTPUT:
You don’t need to click on this. Just take mouse on it. Alert message will be displayed.
PROGRAM:
Assignment: when I take mouse on this, input field has to show me yellow color. Can be done by combination of CSS and
JAVA.
Vizu.chowdary@gmail.com JSCRIPT - 82
PROGRAM: (this program is included with FUNCTIONS)
OUTPUT:
Vizu.chowdary@gmail.com JSCRIPT - 83
onsubmit event type:
Another most important event type is onsubmit. This event occurs when you try to submit a form. So
you can put your form validation against this event type.
Here is simple example showing its usage. Here we are calling a validate() function before submitting a
form data to the webserver. If validate() function returns true the form will be submitted otherwise it
will not submit the data.
onmouseover and onmouseout:
These two event types will help you to create nice effects with images or even with text as well.
The onmouseover event occurs when you bring your mouse over any element and the onmouseoutoccurs
when you take your mouse out from that element.
Vizu.chowdary@gmail.com JSCRIPT - 84
HTML 4 Standard Events
The standard HTML 4 events are listed here for your reference. Here script indicates a Javascript function to be
executed against that event.
Vizu.chowdary@gmail.com JSCRIPT - 85
Vizu.chowdary@gmail.com JSCRIPT - 86
FUNCTIONS
A function is a group of reusable code which can be called anywhere in your program. This eliminates
the need of writing same code again and again. This will help programmers to write modular code. You
can divide your big program in a number of small and manageable functions.
Like any other advance programming language, JavaScript also supports all the features necessary to
write modular code using functions.
You must have seen functions like alert() and write() in previous source. We are using these function
again and again but they have been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section will explain you how to write your own
functions in JavaScript.
Function Definition:
Before we use a function we need to define that function. 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. The basic syntax is shown here:
Vizu.chowdary@gmail.com JSCRIPT - 87
CALLING THE FUNCTION
To invoke a function somewhere later in the script, you would simple need to write the name of that function
as follows:
Vizu.chowdary@gmail.com JSCRIPT - 88
OUTPUT:
Vizu.chowdary@gmail.com JSCRIPT - 89
ADVANTAGES:
Function like function modules.
Functions are re-usable.
Vizu.chowdary@gmail.com JSCRIPT - 90
Function Parameters:
Till now we have seen function without a parameters. But 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.
A JavaScript function can have an optional return statement. This is required if you want to return a value from
a function. This statement should be the last statement in a function.
For example you can pass two numbers in a function and then you can expect from the function to return
their multiplication in your calling program.
E.G.
This function takes two parameters and concatenates them and return resultant in the calling program:
<script type="text/javascript">
<!--
function concatenate(first, last)
{
var full;
<script type="text/javascript">
<!--
var result;
result = concatenate('Zara', 'Ali');
alert(result );
//-->
</script>
Vizu.chowdary@gmail.com JSCRIPT - 91
FUNCTION PARAMETERS (SINGLE PARAMETER)
WE CAN USE FUNCTIONS EXTENSIVELY JUST LIKE IMPORT / EXPORT PARAMETERS
QUESTION: WHAT IS DIFFERENCE BETWEEN EXPORT PARAMETERS AND RETURN PARAMETERS FOR AN ABAP
FUNCTION MODULE?
Vizu.chowdary@gmail.com JSCRIPT - 92
FUNCTION PARAMETERS (MULTIPLE PARAMETER)
Vizu.chowdary@gmail.com JSCRIPT - 93
USING ABOVE PROGRAM FOR RE-USE, WITH SINGLE DOCUMENT.WRITE
Vizu.chowdary@gmail.com JSCRIPT - 94
DEBUGGING
Press F12.
Vizu.chowdary@gmail.com JSCRIPT - 95
Close this
Vizu.chowdary@gmail.com JSCRIPT - 96
Right click on 7th line and select Add breakpoint. (or) click on 7th line
Break Point
Vizu.chowdary@gmail.com JSCRIPT - 97
We can see Paused in debugger. Step-over
F8
Step out of Current Function (Shift + F11)
Vizu.chowdary@gmail.com JSCRIPT - 98
First, we will see how we can go for next step.
Vizu.chowdary@gmail.com JSCRIPT - 99
Now let’s change the value.
Go to the CONSOLE
The is the value that we can see
Press ENTER.
ONCLICK is the in-built event provided by HTML guys, that if you want to interact with java script
OUTPUT:
When we want to re-use same alert or multiple times. This is not best way. So we do is create something called as
function (like F.M for us). See in next program
function clickMe(){
OutPut:
OUTPUT:
Here I am defining inside the function
Next example I am calling outside the function.
At alert level it is SAP UI5
Output:
When I run it. It is netweaver Gateway training
OUTPUT:
It is SAP UI5
Output:
Here we have an error.
Execute.
Press F12 on browser.
Unless and until we execute the function, localvar is not known to the system
OUTPUT:
OUTPUT:
Example
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
Initially null
Press on OK
OUTPUT:
Press on This is Para1
This is the way, how i can get into the DOM and display (getElementByid)
Click
This is one of the way how JAVASCRIPT works on the DOM by using getElementById().
We will get descript over here, for each single step execution. We can also edit here as we do in ABAP debugging.
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get
confirmation on any input or to have a kind of input from the users.
Here we will see each dialog box one by one:
Alert Dialog Box:
(USED TO DISPLAY ALERT POP UP, WHEN USER CLICK ON “OK” TO PROCEED TO NEXT STEP.)
SYNTAX: ALERT (“MESSAGE”);
An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some
text but user does not enter that field then as a part of validation you can use alert box to give warning message as
follows:
<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and
proceed.
<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
alert("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
<html>
<head>
<title> pop up boxes </title>
<script>
alert("welcome to My Web page");
alert("Bye....");
</script>
</head>
<body>
<script>
alert("welcome to body of the page");
alert("BYE......");
</body>
</html>
Click on ok
We Should not use <br> tag here, ALERT() is a method of window object that can’t interpret HTML tags.
If you break text into multiple lines we should use new line escape character. It consist of (\) Back slash symbol
& an alphabet.
EXAMPLE
<script>
alert("1 \n \t 2 \n\t\t 3");
</script>
<head>
<script>
function show_message()
{
alert("it is alert popup");
alert("bye....");
}
</script>
</head>
<body>
<input type = "SUBMIT" onclick = "show-message()" value = "showMe">
</body>
else
{
alert("USER SELECTED CANCEL BUTTON");
}
</script>
</head>
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.
If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel
button confirm() returns false. You can use confirmation dialog box as follows:
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
Syntax:
PROMPT (“SOMETEXT”, “DEFAULT VALUE”);
A prompt box is used to input a value before entering a page. When a prompt box pops up, a user should click
either OK or CANCEL.
If user select OK, it returns the INPUT value.
If user select CANCEL, it returns NULL
<head>
<script>
xyz = prompt("enter any number", "9");
alert("entered Number is: " +xyz);
</script>
</head>
PROGRAM - 5:
Object Properties:
Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object.
Object properties are usually variables that are used internally in the object's methods, but can also be globally visible
variables that are used throughout the page.
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
Example:
Following is a simple example to show how to get a document title using "title" property of document object:
var str = document.title;
Object Methods:
The methods are functions that let the object do something or let something be done to it. There is little difference
between a function and a method, except that a function is a standalone unit of statements and a method is attached to
an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing complex
mathematical operations on a group of local properties and parameters.
Example:
Following is a simple example to show how to use write() method of document object to write any content on the
document:
document.write("This is test");
This example demonstrates how to create an object: This example demonstrates how to create an object with a
User-Defined Function. Here thiskeyword is used to refer to
the object that has been passed to a function:
<html>
<head>
<html>
<title>User-defined objects</title>
<head>
<script type="text/javascript">
<title>User-defined objects</title>
var book = new Object(); // Create the object
<script type="text/javascript">
book.subject = "Perl"; // Assign properties to the object
function book(title, author){
book.author = "Mohtashim";
this.title = title;
</script>
this.author = author;
</head>
}
<body>
</script>
<script type="text/javascript">
</head>
document.write("Book name is : " + book.subject +
<body>
"<br>");
<script type="text/javascript">
document.write("Book author is : " + book.author +
var myBook = new book("Perl", "Mohtashim");
"<br>");
document.write("Book title is : " + myBook.title +
</script>
"<br>");
</body>
document.write("Book author is : " + myBook.author +
</html>
"<br>");
</script>
</body>
</html>
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Syntax:
with (object){
properties used without the object name and dot
}
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
HTML
Java Script works on the DOM. Whenever Browser Executes the HTML. It creates a DOM.
ARRAYS
WHAT IS THE SIGNIFICANCE OF ARRAY?
Stack of values where we can manipulate.
We can add-up multiple values, instead of holding a single value in form of variable.
Collection of elements.
Arrays are not used extensively. Before OOP’s they used this. Let me add up some java script over here also.
OUTPUT:
There will be no output for above example. We need to call the function.
OUTPUT:
Form we can use, when we want send the data from this page to another page (or 3rd party).
Here we are working on single document. So the code above.
Note: DOM not only holds element (model) and also holds value that we had provided.
With help of DOM we can retrieve value with in the input.
Output:
Output:
Explanation…………………..
3) Concatenation
4) Assigned valued to the inner part of para
2nd file
Now requirement is, if user doesn’t enter any values, it should not navigate to second page. Should remain on same
page.
Continues………………..
Now it works.
IMPORTANT POINT:
REGULAR EXPRESSION by which we can validate whether particular string contains dot (.) or comma (,) or special
characters in JQUERY
Output:
==================================================================================================
Result is below
=================================================================================================
=============================================================================================
STEP OVER
Give
Var txt1 = document.createTextNode(“click me”);
Assignment:
Create a table using JSCRIPT. It should be division <div> and content. ,<div id = “content”> </div>-
SAP JAVA
.NET PHP
First display the table
Add text - button
Delete - table
Update table – text type, input type
IMPORTANT NOTE:
Still now we created an element, read the element values, setAttribute(will return values), Modified text.
OUTPUT:
click on this ----
it will be deleted. These all are called as CRUID methods in SAP UI5
Execute
PRESS F12
Click on REFRESH
Click on STEPOVER.
The relation between <div> and <label> here is Parent and Child.
OUTPUT:
In output it will not show, because we haven’t added to the div. so let’s add it now.
OUTPUT:
END OF
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXEMPLOYEE FILED USING JAVASCRIPTXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I have to validate user naming. Somebody writes the numeric which is not allowed.
E.g.
Pattern used by user for street is
If user would validate with alpha, then numeric should not allow end user to do that.
1:10
\d{3}
\d{1,3}- (if I specify {1, 3} = there can be minimum 1 and maximum 3 digits)
Finally \.
Output is
/\d{1,3}\s\w+\s\w+\./
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
/^\d{1,3}\s\w+\s\w+\.$/
Email: info_a-director2.org@v-jay.in
Can start with capital letter, small letter and 0 – 9. My email id can also start with _ and -
It can contain .
^([A-Za-z0-9_\-\.]) {1,}
Next is @ = \@
^([A-Za-z0-9_\-\.]){1,}\@
^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,3})$
emailCode: ^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,3})$
(1) Valid
(2) invalid
(3) invalid
(4) valid
BRACKETS:
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of
characters. (Or)
Brackets are used to find a range of characters:
Expression Description
[...] Any one character between the brackets.
[^...] Any one character not between the brackets.
[^abc] Find any characters NOT between the brackets (don’t allow those characters)
[0-9] It matches any decimal digit from 0 through 9.
Find any digit between the brackets.
[^0-9] Find any digit NOT between the brackets.
[a-z] It matches any character from lowercase a through lowercase z.
(or) Find any characters between a-z
[A-Z] It matches any character from uppercase A through uppercase Z.
(or) Find any characters between A-Z
[a-Z] It matches any character from lowercase a through uppercase Z.
[abc] Find any characters between the brackets
Meta Description
character
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx
OUTPUT:
EXAMPLE
OUTPUT:
Property
Initial I gave vejaykumaar b, but getName has changed value from vejaykumaar b to BVK
All JavaScript objects inherit the properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype.
The Object.prototype is on the top of the prototype chain.
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.
------------------------------------------------------------------------------------------------------------------------------------------------------
Similarly I can create one more EMP2
PROTOTYPE is like a CONSTRUCTOR. That is what the point we discussed above (POINT: The standard way to create an
OBJECT PROTOTYPE is to use an OBJECT CONSTRUCTOR FUNCTION.
)
expand
For the prototype I am adding a new property/new variable/new attribute to existing this person
Prototype are the abstract objects which can be used by referring to some third parties
WHAT IS PROTOTYPE?
Prototype is an object. Which cannot be used directly, but can be referred.
Prototype is a constructor.
Constructor accepts the initialized values.
USAGE:
Easy way to add effects (animation effects).
BENEFITS:
- Fast loading library.
- Cross browser compatibility: when we use JAVASCRIPT, some fonts look huge and some effects are not
compatible with other browsers. These type of issues we may get when we use JAVASCRIPT. When we use
JQUERY most of the browser compatibility issues are resolved.
- Easy Ajax implementation. (AJAX – Asynchronous Java Script as XML.) {AJAX is JAVASCRIPT CODE}
ASYNCHRONOUS: without user’s permission, it is going to the back-end server, goes to application server, retrieves,
and validates whatever.
What happens with AJAX is, without user event (permission) we can send request to the back-end and we can
retrieve the data.
When I mouse over on stars, goes back and fetches the data.
DOWNLOAD:
JQUERY library from jquery.com – show how to download and placing JQUERY.
Jquery is bundle of pre-defined functions and the objects of JAVASCRIPT. So we need to download that.
Click on download
Using ID
# stands for ID and . Stands for class of HTML attribute (id, class, name)
INPUT is an element.
TYPE gives us what type of UI element we want to display (i.e. input field).
SIGNIFICANCE OF ID HERE (one usage is css – we can put background color, second usage is - we are fetching the value
in JAVASCRIPT)
SIGNIFICANCE OF CLASS (only for css - style)
SIGNIFICANCE OF NAME (name for JavaScript [works at client side] + Server Side Program)
Click on
NOTE: Keep Jquery file which we downloaded and our html file in same folder.
Hide is a method
This is selector can be id / class / para. ($(p).hide())
What we done here, we have writing single line of code, instead of JAVASCRIPT multiple lines.
Execute.
Goto JQUERY.COM
Click on this
OUTPUT:
OUTPUT:
OUTPUT:
READY: before appears on the web page. When it gets ready then what ever the stuff we want to make we can write
inside *$(‘myPara’).fadeIn(4000)+
NOTE:
YOUTUBE
Jquery tutorials for beginners quenton
Whatever the possibilities are there with JQUERY are possible with JAVASCRIPT
Whatever the functionality that JQUERY has, it is pretty much possible with JAVASCRIPT as well.
WE CAN VALIDATE INPUT FIELD USING JQUERY. WHICH IS ALSO POSSIBLE WITH JSCRIPT. WHY SO?
JQUERY is built over JSCRIPT to reduce the complexity.
JQUERY is inner built using JAVASCRIPT. So whatever possibilities are there with JQUERY, pretty much possible
with JSCRIPT. BUT NOT VICE VERSA.
One of the limitation that I had observed is, cannot create element using JQUERY.
JQUERY USES DIFFERENT OPERATION LIKE IF, WHILE, DOWHILE, FOR LOOP.
If we don’t know JAVASCRIPT, we can work on JQUERY. One or someday we need to compare JSCRIPT. Because
JQUERY is not fully replacement of JavaScript.
With the help of JQUERY we are minimizing code and we are making whatever the stuff that is the cross browser
compatibility.
HIDING A PARA
jQuery() – function Event what should happen, I will write inside function
on which part
I need to click (on para)
On click of that what should happen (should hide). Which element should hide is para
OUTPUT:
Click on this
OUTPUT:
OUTPUT:
Click on this
OUTPUT:
And so on………………
Same as above
OUTPUT:
When you click on LOGIN-1 and LOGIN-2 you will get alert message.
Key value
OUTPUT:
OUTPUT:
OUTPUT:
When I click on LOGIN-2, LOGIN-1 has to be disabled / LOGIN-1 has to become white color.
QUESTIONS:
OUTPUT: execute & click on the image. Disappears after some time too slowly.
OUTPUT: execute & click on the image. Disappears after some time too slowly and comes back to visible.
Click on
OUTPUT:
3) SLIDEUP
5) PADDING OF 200PX
There is padding of 200 px. It adjust in such way that top 200px and side 200px and all sides.
$(shortcut) to JQUERY.
What is $(this)?
‘this’ stands for referring element on which event is triggered.
ELEMENT SELECTORS?
HTML Element level
How to select particular element.
I can specify it as input field, check box (type = “checkbox”), radio button (type = “radiobutton”).
I can specify type, where user can input.
==============================THE END==============================
When you click a URL to reach to a page X but internally you are directed to another page Y that simply happens because
of page re-direction. This concept is different from JavaScript Page Refresh.
There could be various reasons why you would like to redirect from original page. I'm listing down few of the reasons:
You did not like the name of your domain and you are moving to a new one. Same time you want to direct your
all visitors to new site. In such case you can maintain your old domain but put a single page with a page re-
direction so that your all old domain visitors can come to your new domain.
You have build-up various pages based on browser versions or their names or may be based on different
countries, then instead of using your server side page redirection you can use client side page redirection to land
your users on appropriate page.
The Search Engines may have already indexed your pages. But while moving to another domain then you would
not like to lose your visitors coming through search engines. So you can use client side page redirection. But
keep in mind this should not be done to make search engine a fool otherwise this could get your web site
banned.
Example 1:
This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you
just need to add a line in your head section as follows:
You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit
time delay to load a new page. Following is the simple example to implement the same:
Here setTimeout() is a built-in JavaScript function which can be used to execute another function
after a given time interval.
Example 3:
Following is the example to redirect site visitors on different pages based on their browsers :
The void is an important keyword in JavaScript which can be used as a unary operator that appears before its
single operand, which may be of any type.
This operator specifies an expression to be evaluated without returning a value. Its syntax could be one of the
following:
<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()
or:
void(func())
javascript:void(func())
//-->
</script>
</head>
Example 1:
The most common use for this operator is in a client-side javascript: URL, where it allows you to evaluate an
expression for its side effects without the browser displaying the value of the evaluated expression.
Here the expression alert('Warning!!!') is evaluated but it is not loaded back into the current document:
<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following link to see the result: </p>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following, This won't react at all...</p>
<a href="javascript:void(alert(0))">Click me!</a>
</body>
</html>
Example 3:
Another use for void is to purposely generate the undefined value as follows:
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var a,b,c;
a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</body>
</html>
PROGRAM:
Output:
Output:
Note: alert will not work over here. It has to be enclosed with in the function.
Output:
Click on this
OUTPUT:
Input some value in to this
Press on done
This is the script, validate user name and password here in jscript.
Output:
ADVANTAGE IS RE-USABILITY.
Properties are the values that object has, just as we have like height, complex etc.,
The way that properties reacts based on methods.
Coding pretty easier than procedural language. Easily extendable as we have inheritance.
OLD WAY:
When we say NEW, a memory will be allocated. And that address is referred to person.
Person actual contains the address.
Person is not an object. It is an object reference.
Two objects are created and two references are created. They are not co-related to each other.
Two objects are created and two references are created. They are co-related to each other
Execute
PROGRAM – 9
OUTPUT:
Output:
Output:
Output:
PROGRAM – 11:
Here we are getting values (how many variables are there. It’s totally 4. )