You are on page 1of 42

Javascript english version

1. Introduction

JavaScript is a programming language that permit to develop a dynamic an


interact web pages. It should be noted that JavaScript is a client side script

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

The merits of using JavaScript are:

 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

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.
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

The scope of a variable is the region of your program in which it is defined.


JavaScript variables have only two scopes.
 Global Variables: A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
 Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global
variable with the same name. If you declare a local variable or function
parameter with the same name as a global variable, you effectively hide the
global variable. Take a look into the following example.
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable function checkscope( ) {
var myVar = "local"; // Declare a local variable document.write(myVar);
}
//-->
</script>
3.2 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 allows you to work with three primitive data types:
 Numbers, e.g., 123, 120.50 etc.
 Strings of text, e.g. "This text string" etc.
 Boolean, e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value.

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.

4.1 Arithmetic Operators

JavaScript supports the following arithmetic operators: Assume variable A


holds 10 and variable B holds 20, then
S.NO Operator and Description
1 + (Addition)
Adds two operands Ex: A + B will give 30
- (Subtraction)
Subtracts the second operand from the first Ex: A - B will
give -10
* (Multiplication) Multiply both operands Ex: A * B will give
200
/ (Division)
Divide the numerator by the denominator Ex: B / A will give
2
% (Modulus)
Outputs the remainder of an integer division Ex: B % A will
give 0
++ (Increment)
Increases an integer value by one Ex: A++ will give 11
-- (Decrement)
Decreases an integer value by one Ex: A-- will give 9
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" +
10 will give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
<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);
/-->
</script>
<p>Set the variables to different values and then try...</p> </body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
Set the variables to different values and then try...
4.2 Comparison Operators
JavaScript supports the following comparison operators: Assume variable
A holds 10 and variable B holds 20, then:
Operator and Description
== (Equal)
Checks if the value of two operands are equal or not, if
yes, then the condition becomes true.
Ex: (A == B) is not true
!= (Not Equal)
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
> (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
< (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
>= (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.
<= (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.
6
Ex: (A <= B) is true.

4.3 Logical Operators


S.No Operator and Description
&& (Logical AND)
If both the operands are non-zero, then the condition
becomes true. Ex: (A && B) is true.
|| (Logical OR)
If any of the two operands are non-zero, then the
condition becomes true. Ex: (A || B) is true
! (Logical NOT)
Reverses the logical state of its operand. If a condition is
true, then the Logical NOT operator will make it false.
Ex: ! (A && B) is false.

4.4 Assignment Operators


Operator and Description
= (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
+= (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
-= (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
*= (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
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns
the result to the left operand.
Ex: C /= A is equivalent to C = C / A
%= (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

4.5 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.
S no : (Conditional )
If Condition is true? Then value X : Otherwise value Y

<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:

if statement - use this statement to execute some code only if a specified


condition is true
•if...else statement - use this statement to execute some code if the
condition is true and another code if the condition is false
•if...else if....else statement - use this statement to select one of many
blocks of code to be executed
•switch statement - use this statement to select one of many blocks of
code to be executed
a) If Statement
Use the if statement to execute some code only if a specified condition is
true.
Syntax
if (condition)
{
code to be executed if condition is true

Example

<script type="text/javascript">

//Write a "Good morning" greeting if

//the time is less than 10

var d=new Date();

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

condition is not true.

Syntax

if (condition)

code to be executed if condition is true

} else

code to be executed if condition is not true }

Example

<script type="text/javascript">

//If the time is less than 10, you will get a "Good morning" greeting.

//Otherwise you will get a "Good day" greeting.

var d = new Date();

var time = d.getHours();

if (time < 10)

document.write("Good morning!");

} else {
document.write("Good day!");

} </script>

c) If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be
executed.

Syntax

if (condition1)

code to be executed if condition1 is true

else if (condition2)

code to be executed if condition2 is true

} else

code to be executed if condition1 and condition2 are not true

Example

<script type="text/javascript"> var d = new Date()

var time = d.getHours()

if (time<10)

document.write("<b>Good morning</b>");

else if (time>10 && time<16)


{

document.write("<b>Good day</b>");

} else

document.write("<b>Hello World!</b>");

</script>

d) JavaScript Switch Statement


Syntax
switch(n) {
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</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!="")
{

document.write("Hello " + name + "! How are you today?");


}
} </script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt
box" />
</body>
</html>
8 JavaScript Functions
a) How to Define a Function
b) Syntax
function functionname(var1,var2,...,varX) {
some code
}
The parameters var1, var2, etc. are variables or values passed into
the function. The { and the } defines the start and end of the
function.
Note: A function with no parameters must include the parentheses
() after the function name.
Note: Do not forget about the importance of capitals in JavaScript!
The word function must be written in lowercase letters, otherwise
a JavaScript error occurs! Also note that you must call a function
with the exact same capitals as in the function name.
Example
<html>
<head>
<script type="text/javascript"> function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()"
/> </form>
</body>
</html>
c) The return Statement
The return statement is used to specify the value that is returned
from the function. So, functions that are going to return a value
must use the return statement.
The example below returns the product of two numbers (a and b):
Example
<html>
<head>
<script type="text/javascript"> function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>

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{

Sequence dinstruction sequence dinstruction

} }while(condition)

</script> </script>

<script>

For (initialisation ; condition ; incrémentation) {

Sequence of instructions

Example :

<Script>

For( var i=1 ;i<=5 ; i++){

Alert(`literation `,i);

</Script>

9.1 JavaScript Break Statements

The break Statement

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;

document.write("The number is " + i); document.write("<br />");

</script>

</body>

</html>

9.2 The continue Statement

The continue statement will break the current loop and continue with the next
value.
Example

<html>

<body>

<script type="text/javascript"> var i=0

for (i=0;i<=10;i++)

if (i==3)

{ continue;

document.write("The number is " + i); document.write("<br />");

} </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.

An array can be defined in three ways.

The following code creates an Array object called myCars:

1:

var myCars=new Array(); // regular array (add an optional integer


myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";

myCars[2]="BMW"

2:

var myCars=new Array("Saab","Volvo","BMW"); // condensed array

3:

var myCars=["Saab","Volvo","BMW"]; // literal array

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

The syntax of concat() method is as follows:

array.concat(value1, value2, ..., valueN);

Parameter Details

valueN : Arrays and/or values to concatenate to the resulting array.

Return Value

Returns the length of the array.

Example

Try the following example.

<html>

<head>

<title>JavaScript Array concat Method</title>

</head>

<body>

<script type="text/javascript">

var alpha = ["a", "b", "c"];

var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);

document.write("alphaNumeric : " + alphaNumeric );

</script>

</body>

</html>
Output

alphaNumeric : a,b,c,1,2,3

Syntax

Its syntax is as follows:

Array.pop();

Return Value

Returns the removed element from the array.

Example

Try the following example.

<html>

<head>

<title>JavaScript Array pop Method</title>

</head>

<body>

<script type="text/javascript">

var numbers = [1, 4, 9];

var element = numbers.pop(); document.write("element is : " + element );

var element = numbers.pop();

document.write("<br />element is : " + element ); </script>

</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

Its syntax is as follows:

Array.push();

Parameter Details

element1, ..., elementN: The elements to add to the end of the array.

Return Value

Returns the length of the new array.

Example

Try the following example.

<html>

<head>

<title>JavaScript Array push Method</title>

</head>

<body>

<script type="text/javascript">

var numbers = new Array(1, 4, 9);

var length = numbers.push(10);

document.write("new numbers is : " + numbers );

length = numbers.push(20);

document.write("<br />new numbers is : " + numbers ); </script>

</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.

 Data Format Validation - Secondly, the data that is entered must be

checked for correct form and value. Your code must include appropriate logic to
test correctness of data.

Example

We will take an example to understand the process of validation. Here is a


simple form in html format.

<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>

</td>
</tr>

<tr>

<td align="right"></td>

<td><input type="submit" value="Submit" /></td> </tr>

</table>

</form>

</body>

</html>

Basic Form Validation

<script type="text/javascript">

<!--

// Form validation code will come here. function validate()

if( document.myForm.Name.value == "" ) {

alert( "Please provide your name!" ); document.myForm.Name.focus() ;

return false;

if( document.myForm.EMail.value == "" ) {

alert( "Please provide your Email!" );

document.myForm.EMail.focus() ;

return false;

if( document.myForm.Zip.value == "" ||


isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5
)

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;

return false;

if( document.myForm.Country.value == "-1" ) {

alert( "Please provide your country!" );

return false;

return( true );

//-->

</script>

Data Format Validation

Now we will see how we can validate our entered form data before submitting it
to the web server.

The following example shows how to validate an entered email address. An


email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must
not be the first character of the email address, and the last dot must at least be
one character after the ‘@’ sign.

Example

Try the following code for email validation.

<script type="text/javascript"> <!--


function validateEmail(){

ar emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@");

dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 ))

alert("Please enter correct email ID") document.myForm.EMail.focus() ;

return false;

return( true );

//-->

</script>

What are Cascading Style Sheets?

The Cascading Style Sheets (CSS) language is:

•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.

By using CSS, you can also:


•Control text formatting and location on the page.

•Eliminate the need for tables as a layout tool.

•Create logos merely using text, instead of having to rely on graphics.

These changes make pages more accessible to a wider audience.

the Cascading Style Sheets (CSS) Language

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.

To add a comment, separate the text of the comment between /* and */

For example:

/*

Color Stylesheet: Provides colors from the University palette as classes

*/

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:

h1 { color: green; font-size: 36pt; font-weight: bold;}


The emphasized phrase “most important” in this example would display as italicized, bolded, green, 36
point font.

The em inherits the styles (green, 36 point, bold) from its parent – h1.

CSS Locations

Style information can be located:

•External to the pages in a site (the CSS rules are listed in a separate file and linked to the
HTML files).

•Internal to each page.

•Inline with individual tags.

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.

a) CSS: External location


There are two methods you can use to link web pages to an external style sheet: <link>
and @import.
 The <link> method was introduced with CSS 1, and specifically links an HTML
document to a CSS file. With the <link> method, you can specify the media type using
the media="type" attribute. (See below for an example.)
 The @import method was introduced with CSS 2, and is used to import style sheets
into web pages, XML files, or even other style sheets. With the @import method, you
can specify the media type by adding an @media rule. (See below for an example.)

HTML document 2, using the @import and media method: <head>

<style type="text/css">

<!--

@import url("basic.css") all;


@import url("print.css") print;

-->

</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”>

CSS: Internal location


Style information can also be included in the <head> section of an individual web page. This tends to
work best when a single page needs to have a slightly different look than the rest of the site. If you
plan to apply these styles to more than one web page, it is more useful to create an external style
sheet and link the web pages to that style sheet.

EXAMPLE: A web page using internal styles

CSS: Inline location

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

Grouping Styles and Selectors

 Multiple styles – Each rule can include multiple styles, using semicolons to separate
them.

h2 {color: darkblue; font-style: italic;}

 Multiple selectors. Additionally, multiple selectors that have the same styles can be
grouped, using commas to separate them.

h1, h2, h3 {font-style: italic;}

 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:

<ul><li><strong><em> blah </em></strong></li></ul>


 Direct child selectors . Direct child selectors allow you to specify that something will
change, but only when immediately inside another element. With the style below, only
those strong elements that are directly inside h1 will be purple; no strong tags deeper
within the sheet will be purple:
h1 > strong {color: purple;}
 Adjacent selectors . Adjacent selectors allow you to specify that something will change
only when preceded by something else. In the style below, only those links that are
preceded by an h2 will be green:
h2 + a {color: green;}
Elements being modified by adjacent selectors appear immediately after one another
Using the style above, this link would be green:
<h2>Visit Stanford!</h2><a href="http://www.stanford.edu">click here</a>.
But this link would not:
<h2>Visit Stanford! <a href="http://www.stanford.edu">click here</a></h2>.
 By attribute. You can also group selectors by attribute. In the example below, text that
is inside centered h2 tags (<h2 align="center">) will be surrounded by a dotted border:
h2[align="center"] {border: dotted;}
this table summarizes some frequent selectors
A selector description
* Select all element(universal selector)
A,B Select two element A and B
AB Select element B which is contained by A
A[attribute`s name] Select all the element A with the attribute
indicated
A[attribute `name*= value] Select all the element A where the value
is given
A+B Select the first B follow by A
A>B B are direct child and it will be selected

Block and inline element


All html elements are either bloc element or inline elements. The table below will
establish the difference between inline and bloc elements
Block element Inline element
Start to next line Continue to the same line
Occupies all the width available le Occupies only the necessary width
Contains nested element which can be Contains nested element which can be
inline or block only the inline element

Example of block and inline elements


Block elements Inline element
P em
H1, h2, h3, h4, h5, h6 strong
Ol ul, dl mark
Li a
Table img
Div span

Classes and IDs


HTML has two attributes that make CSS even more useful: class and ID. They make it
easy to apply style to just about any tag.
Classes can describe a generic style that can be applied to any HTML element, or can
be created for specific elements. When defining a style for elements with a particular
class attribute in the Style Sheet, declare a rule using a dot (.) followed by the class
name. To limit the style to a particular element with that class attribute, use a selector
combining the tag name with a dot followed immediately by the class name.
The following rule would apply to any element with the attribute class="shade": .shade
{ background: yellow; }
The following rule would apply only to paragraph tags with the class shade
(<p class="shade">):
p.shade { background: red; }
IDs are similar to classes, but IDs are unique. They can only be used with one instance
of an element within a document. When defining a CSS rule using an ID- based
selector, use a number sign (#) followed by the style name. To limit the style to a
particular element with that ID attribute, use a selector combining the tag name with a
# and then the ID name.

Span and Div

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).

.neatstuff {font-family: Comic Sans MS;}

In the HTML:

<span class="neatstuff">This is in Comic Sans</span>

Using CSS to Change Text Properties

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.

h1 { word-spacing: 1.2 em;}

 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.

address {letter-spacing: 1px;}

 text-decoration. This property defines the decorations that are to be added to the
element (underline, overline, line-through, blink, none).

a:link {text-decoration: underline;}

a:hover {text-decoration: 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; }

In CSS 2, the following font properties have been added:


•direction – used to specify the text direction/writing direction body { direction: rtl;}
•text-shadow – used to specify the shadow effect added to text. There are four values:
1The color of the text-shadow
2The X-coordinate of the text-shadow, relative to the text
3The Y-coordinate of the text-shadow, relative to the text
4.The blur radius (amount of space that the shadow text will be “stretched”) of the
text-shadow.
h1 { text-shadow: #999 1px 1px 5px; }
Colors and Background
Colors an be summarized below

The Box Model – height, width, padding, border, margin, outline


When a browser draws an object on a page, it places it into an invisible rectangular
space called a “bounding box.”
You can specify the size, look, and feel of the margins, the padding, the border, and
the content of that bounding box.
In CSS, the width property is defined as the distance between the left and right edges
of the bounding box that surrounds the element’s content.
Likewise, the height property is defined in CSS as the distance between the top and
bottom edges of the bounding box.
If no !doctype is defined in the HTML, Internet Explorer goes into “quirks mode” and
interprets CSS box styles differently than most other web browsers. In this mode,
Internet Explorer interprets the width and height properties to also include the border
and padding belts that surround the element’s bounding box.
internet Explorer will interpret the box model using the CSS standard if the HTML is
written using a declared !doctype.
For example, this web page was created using the XHTML 1.1 doctype:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

Tables and CSS


Although you should never use tables to control page layout, tables can and should be
used to list data in tabular format. You can use CSS to greatly improve the look and
feel of your tables.
The CSS styles you can apply to a table include:
•Borders
 oborder. As mentioned earlier, used to define a border.
table, th, td { border: solid thin pink;}
 border-collapse. This property (collapse, separate, inherit) sets
whether the table borders are collapsed into a single border or detached as in
standard HTML.
table { border-collapse: collapse;}
 border-style. As mentioned earlier, this property (dotted, dashed,
solid, double, groove, ridge, inset, outset) sets the style of borders. table { border-
style: dotted;}
 border-color. As mentioned earlier, this property sets the color of the
border (color name, hexadecimal code, or rgb value) table { border-color:
rgb(100%,0,0);}
 border-spacing. This property (width and height) sets the distance
between the borders of adjacent cells. Only affects tables whose
borders are detached (border-collapse: separate;).
table { border-collapse: separate; border-spacing: 5px 10px;}
•Other table properties:
 width. This property sets the width of the element (in pixels,
percentage, or em).
table { width: 85%;} td, th { width: 150px;} tr { width: 1.5em;}
 height. This property sets the height of the element (in pixels,
percentage, or ex).
table { height: 85%;} td, th { height: 150px;}
tr { height: 1.5ex;}
 padding. This sets the amount of space between the edge of the
content and the border. td { padding: 15px;}

php
php is also a script language that help to

You might also like