Javascript English Version-1
Javascript English Version-1
1. Introduction
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 initiates explicitly or implicitly.
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
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
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
2. Placement of JavaScript
There are two methods to include JavaScript into a html code: internal and
external.
A. JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to 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 all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as
shown above.
For example, you can keep the following content in filename.js file and then
you can use sayHello function in your HTML file after including the filename.js
file.
function sayHello() {
alert("Hello World")
}
B. using JavaScript internally
<html>
<head> <title>le titre du sit </title>
<script type=”text/javascript”>// or <script language=”JavaScript” >
Document.write(“welcome”);
</Script>
</head>
<body>
</body>
</html>
JavaScript can be inserted at any part of html document: in the head as
shown above but also in the body.
3. JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables
are declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable
initialization at the time of variable creation or at a later point in time when you
need that variable.
script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note:
JavaScript is untyped language. This means that a JavaScript variable can hold
a value of any data type. Unlike many other languages, you don't have to tell
JavaScript during variable declaration what type of value the variable will
hold. The value type of a variable can change during the execution of a
program and JavaScript takes care of it automatically
3.1 JavaScript Variable Scope
JavaScript operator
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator. JavaScript supports the following
types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Let’s have a look at all the operators one by one.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200; document.write(result);
document.write(linebreak);
document.write ("((a < b? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result); document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
What is the ouput
5 Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
Any text between a // and the end of a line is treated as a comment and
is ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This
may span multiple line
JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the //
comment.
The HTML comment closing sequence --> is not recognized by JavaScript
so it should be written as //-->
6 Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do
this. In JavaScript we have the following conditional statements:
Example
<script type="text/javascript">
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
</script>
b) If...else Statement
Use the if....else statement to execute some code if a condition is true and
another code if the
Syntax
if (condition)
} else
Example
<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
document.write("Good morning!");
} else {
document.write("Good day!");
} </script>
Use the if....else if...else statement to select one of several blocks of code to be
executed.
Syntax
if (condition1)
else if (condition2)
} else
Example
if (time<10)
document.write("<b>Good morning</b>");
document.write("<b>Good day</b>");
} else
document.write("<b>Hello World!</b>");
</script>
7 dialog box
a) Alert Box
An alert box is often used if you want to make sure information comes
through to the user. When an alert box pops up, the user will have to
click "OK" to proceed.
Syntax
alert("sometext");
Example
<html>
<head>
<script type="text/javascript"> function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box"
/>
</body> </html>
b) Confirm Box
A confirm box is often used if you want the user to verify or accept
something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel",
the box returns false.
Syntax
confirm("sometext");
Example
<html>
<head>
<script type="text/javascript"> function show_confirm()
{
var r=confirm("Press a button"); if (r==true)
{
alert("You pressed OK!");
} else
{
alert("You pressed Cancel!"); }
} </script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm
box" />
</body>
</html>
c) Prompt Box
A prompt box is often used if you want the user to input a value before
entering a page.
When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
Syntax
prompt("sometext","defaultvalue");
Example
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter”)
if (name!=null && name!="")
{
9 JavaScript Loops
Loops execute a block of code a specified number of times, or while a specified
condition is true.
<script> <script>
While(condition){ do{
} }while(condition)
</script> </script>
<script>
Sequence of instructions
Example :
<Script>
Alert(`literation `,i);
</Script>
The break statement will break the loop and continue executing the code that
follows after the loop (if any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++){
if (i==3)
{ break;
</script>
</body>
</html>
The continue statement will break the current loop and continue with the next
value.
Example
<html>
<body>
for (i=0;i<=10;i++)
if (i==3)
{ continue;
} </script>
</body>
</html>
10 array
An array can hold all your variable values under a single name. And you can
access the values by referring to the array name.
Each element in the array has its own ID so that it can be easily accessed.
1:
myCars[2]="BMW"
2:
3:
mycars[index] will help to access the element store at the position indicating by
the index
Array Methods
Here is a list of the methods of the Array object along with their description.
Method Description
concat() Returns a new array comprised of
this array joined with other array(s)
and/or value(s).
every() Returns true if every element in this
array satisfies the provided testing
function
filter() Creates a new array with all of the
elements of this array for which the
provided filtering function returns
true.
forEach() calls a function for each element in
the array
indexOf() Returns the first (least) index of an
element within the array equal to the
specified value, or - 1 if none is
found.
join() Joins all elements of an array into a
string.
lastIndexOf() returns the last (greatest) index of an
element within the array equal to the
specified value, or - 1 if none is
found.
map() Creates a new array with the results
of calling a provided function on
every element in this array
pop() Removes the last element from an
array and returns that element.
push() Adds one or more elements to the
end of an array and returns the new
length of the array.
Reduce() Apply a function simultaneously
against two values of the array (from
left-to-right) as to reduce it to a
single value.
reduceRight() Apply a function simultaneously
against two values of the array (from
right-to-left) as to reduce it to a
single value.
reverse() Reverses the order of the elements of
an array -- the first becomes the last,
and the last becomes the first.
shift() Removes the first element from an
array and returns that element
slice() Extracts a section of an array and
returns a new array
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from
an array
Returns a string representing the
array and its elements.
unshift() Adds one or more elements to the
front of an array and returns the new
length of the array.
Length() Give the length of an array
in the following sections, we will have a few examples to demonstrate the usage
of Array methods.
concat (): Javascript array concat() method returns a new array comprised of this
array joined with two or more arrays.
Syntax
Parameter Details
Return Value
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Output
alphaNumeric : a,b,c,1,2,3
Syntax
Array.pop();
Return Value
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
</body>
</html>
push ()
Javascript array push() method appends the given element(s) in the last of the
array and returns the length of the new array.
Syntax
Array.push();
Parameter Details
element1, ..., elementN: The elements to add to the end of the array.
Return Value
Example
<html>
<head>
</head>
<body>
<script type="text/javascript">
length = numbers.push(20);
</body>
</html>
FORM VALIDATION
Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button. If the data
entered by a client was incorrect or was simply missing, the server would have
to send all the data back to the client and request that the form be resubmitted
with correct information. This was really a lengthy process which used to put a
lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.
Basic Validation - First of all, the form must be checked to make sure all
the mandatory fields are filled in. It would require just a loop through each field
in the form and check for data.
checked for correct form and value. Your code must include appropriate logic to
test correctness of data.
Example
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<td align="right">Name</td>
</tr>
<tr>
<td align="right">EMail</td>
</tr>
<tr>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
</table>
</form>
</body>
</html>
<script type="text/javascript">
<!--
return false;
document.myForm.EMail.focus() ;
return false;
return false;
return false;
return( true );
//-->
</script>
Now we will see how we can validate our entered form data before submitting it
to the web server.
Example
dotpos = emailID.lastIndexOf(".");
return false;
return( true );
//-->
</script>
•Used to describe the presentation (the look and feel) of a document written in a markup
language.
•Primarily used to style documents written in HTML/XHTML (web pages), but it can also be
used to style XML and other markup languages.
•Made up of rules. Web browsers interpret these rules in a specific, top-to- bottom, or
cascading manner (that is, if two rules are in conflict with one another, the last rule listed
overrides the previous rule). The CSS rules control the look, or style of the content of these
markup languages.
CSS contains rules. Each rule consists of a selector and a declaration (which in turn is made up
of a property and a value)
In this example P is the selector; color: blue; is a declaration where color is the property and blue is the
value
Comments
Adding comments in your CSS will help you (and future developers) understand the exact reasoning
and methodology you utilized when writing a particular CSS rule.
For example:
/*
*/
Inheritance
Under both HTML and CSS rules, elements that are inside of other elements (this is known as a child
element) inherit the style of the parent.
For example, suppose you have a web page with the following HTML code: <h1>The <em>most
important</em> headline information</h1>
And the web page is styled with the following CSS code:
The em inherits the styles (green, 36 point, bold) from its parent – h1.
CSS Locations
•External to the pages in a site (the CSS rules are listed in a separate file and linked to the
HTML files).
Generally, creating an external style sheet file is the preferred method. To take full advantage
of CSS, the Style Sheet for a site should be in an external file, so that any changes made there
will apply throughout the site. This also means that only one style document has to be
downloaded for a single site, making the web pages load faster.
<style type="text/css">
<!--
-->
</style>
</head>
In this second example all and print are value of the attribute media.
We could have written in the first example <link ref=”styleSheet” href=”style.css” media=”all”>
For extreme control, style information can be included in an individual tag. The style effects
only that tag and no others in the document. This option is most useful for those rare
occasions when a single tag needs to have a slightly different style.
EXAMPLE: A web page using inline style
Multiple styles – Each rule can include multiple styles, using semicolons to separate
them.
Multiple selectors. Additionally, multiple selectors that have the same styles can be
grouped, using commas to separate them.
Contextual selectors. Contextual selectors allow you to specify that something will
occur only when it is used in conjunction with something else. In the style below, em
will display in red, but only when it occurs within li within ul:
ul li em {color: red;}
Elements being modified by contextual selectors need not appear immediately inside one
another. For example, using the style above with the HTML below, blah would still be red text:
There are two tags that are particularly useful when using CSS: <span> and <div>. They are
both container tags that have minimal formatting associated with them.
Using <span> and <div> tags in conjunction with classes and IDs allows for great flexibility in
creating pages. The <span> tag is an empty inline element that can be used to hold text. It is a
generic wrapper for content that, by itself, does not do or represent anything.
The <div> tag is an empty block element designed to hold a division of text. Like the <span>
tag, it is a generic container for content that by itself does not do or represent anything
(except to place the content onto its own line).
In the HTML:
With CSS, you can define how text appears when the browser renders it. The
textual properties are:
word-spacing. This property defines the spacing between words. See Unit
Measurements on page 8 for details on the units of measurement you can use.
letter-spacing. This property defines the spacing between letters. See Unit
Measurements on page 8 for details on the units of measurement you can use.
text-decoration. This property defines the decorations that are to be added to the
element (underline, overline, line-through, blink, none).
vertical-align. This property defines the vertical alignment of the element. The vertical
alignment choices are:
baseline – align the baseline (or bottom) of the element
middle – align the vertical midpoint of the element
sub – subscript the element
super – superscript the element
text-top – align the top of the element with the top of the font
text-bottom – align the bottom of the element with the bottom of the
font
top – align the top of the element with the tallest element on the line
bottom – align the bottom of the element with the lowest element on
the line imagetext { vertical-align: middle}
text-transform. This property defines the case of the font (uppercase, lowercase,
capitalize, none) h2 { text-tranform: uppercase;}
text-align. This property defines the alignment of the text within the element (left,
right, center, justify) h1 { text-align: cent}
ext-indent. This property defines the amount of space to indent the text. See Unit
Measurements on page 8 for details on the units of measurement you can use.
p { text-indent: 20px;}
line-height. This property defines the height of a line. See Unit Measurements on page
8 for details on the units of measurement you can use.
h3 {line-height: 1.2ex;}
white-space. This property defines specifies how white-space inside an element is
handled (normal, nowrap, pre, pre-line, pre-wrap, inherit)
p { white-space: nowrap;}
CSS and Fonts
When choosing a font, there are several things to keep in mind.
Not everyone has the same set of fonts.
If you use a font that the visitor doesn’t have, the page will display in the default font
(usually Times), unless you provide more choices. To do this, add more than one font
in your declaration, and always end with the font family (serif, sans-serif, or
monospace):
font-family: Verdana, Arial, Helvetica, sans-serif
Printed documents tend to look better in Serif fonts (Times New Roman, Georgia, Book
Antiqua, etc.).
Documents to be viewed on-screen tend to look better in Sans-serif fonts (Verdana,
Arial, Helvetica, etc.).
To apply a font to the entire web page, modify the <body> tag in the CSS. For example,
this CSS rule changes the default font for the web page to Verdana: body {font-family:
Verdana;}
To apply a font to a specific letter, word, or series of words, see Span and Div on
in CSS 1, the following font properties can be defined:
•font-family – used to define the font family or generic family names p { font-family:
Verdana, Arial, sans-serif;}
•font-style – used to define the style as either normal (upright), italic (slanted but
using a different glyph than normal), or oblique (slanted but using the same glyph as
normal – oblique looks like italic font distorted). address { font-style: oblique;}
•font-variant – used to display the font in small caps or normal. .important { font-
variant: small-caps;}
•font-weight – used to define how bold the text will be displayed. The choices are:
normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900. ‘normal’ is
equivalent to 400; ‘bold’ is equivalent to 700; bolder and lighter will display the font
one level bolder or lighter than the weight of the parent element.
.veryimportant { font-weight: 900;}
font-size – used to define the size of the font. See Unit Measurements on page 8 for
details on the units of measurement you can use.
body {font-size: medium;
font-size – used to define the size of the font. See Unit Measurements on page 8 for
details on the units of measurement you can use.
body {font-size: medium;}
font – used to combine the various font properties into a single rule.
body { font: Verdana, Arial, sans-serif normal small-caps 400 medium; }
php
php is also a script language that help to