Example Explained @BULLET The DOCTYPE declaration defines the document type

52
Example Explained The DOCTYPE declaration defines the document type The text between <html> and </html> describes the web page The text between <body> and </body> is the visible page content The text between <h1> and </h1> is displayed as a heading The text between <p> and </p> is displayed as a paragraph HTML Tags HTML markup tags are usually called HTML tags. HTML tags are keywords (tag names) surrounded by angle brackets like <html> HTML tags normally come in pairs like <p> and </p> The first tag in a pair is the start tag, the second tag is the end tag The end tag is written like the start tag, with a slash before the tag name Start and end tags are also called opening tags and closing tags <tagname>content</tagname> HTML Elements In HTML, most elements are written with a start tag (e.g. <p>) and an end tag (e.g. </p>), with the content in between: <p>This is a paragraph.</p> 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.

Transcript of Example Explained @BULLET The DOCTYPE declaration defines the document type

Example Explained

The DOCTYPE declaration defines the document type The text between <html> and </html> describes the web page The text between <body> and </body> is the visible page content The text between <h1> and </h1> is displayed as a heading The text between <p> and </p> is displayed as a paragraph

HTML Tags

HTML markup tags are usually called HTML tags.

HTML tags are keywords (tag names) surrounded by angle brackets like<html>

HTML tags normally come in pairs like <p> and </p> The first tag in a pair is the start tag, the second tag is the end

tag The end tag is written like the start tag, with a slash before the

tag name Start and end tags are also called opening tags and closing tags

<tagname>content</tagname>

HTML Elements

In HTML, most elements are written with a start tag (e.g. <p>) and an end tag (e.g. </p>), with the content in between:

<p>This is a paragraph.</p>

JavaScript Placement in HTML FileThere is a flexibility given to include JavaScript code anywhere in an HTML document. Butthere are following most preferred ways to include JavaScript in your HTML file.

Script in <head>...</head> section.

Script in <body>...</body> section.

Script in <body>...</body> and <head>...</head> sections.

Script in and external file and then include in <head>...</head> section.

In the following section we will see how we can put JavaScript in different ways:

JavaScript in <head>...</head> section:

If you want to have a script run on some event, such as when a user clicks somewhere, thenyou will place that script in the head as follows:

<html><head><script type="text/javascript"><!--function sayHello() { alert("Hello World")}//--></script></head><body><input type="button" onclick="sayHello()" value="Say Hello" /></body></html>

This will produce following result:

To understand it in better way you can Try it yourself.

JavaScript in <body>...</body> section:

If you need a script to run as the page loads so that the script generates content in thepage, the script goes in the <body> portion of the document. In this case you would nothave 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>

This will produce following result:

Advertisements

Hello WorldThis is web page body

To understand it in better way you can Try it yourself.

JavaScript in <body> and <head> sections:

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>

This will produce following result:

Advertisements

Hello World

To understand it in better way you can Try it yourself.

JavaScript in External File :

As you begin to work more extensively with JavaScript, you will likely find that there arecases 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 andthen include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTMLcode 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 JavaScriptsource code in a simple text file with extension ".js" and then include that file as shownabove.

For example, you can keep following content in filename.js file and then you canuse sayHellofunction in your HTML file after including filename.js file:

function sayHello() { alert("Hello World")}

The Arithmatic Operators:There are following arithmatic operators supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denumerator B / A will give 2

% Modulus Operator and remainder of after an integer division

B % A will give 0

++ Increment operator, increases integer value by one

A++ will give 11

-- Decrement operator, decreases integer value by one

A-- will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give"a10".

To understand these operators in better way you can Try it yourself.

The Comparison Operators:There are following comparison operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

== Checks if the value of two operands are equal ornot, if yes then condition becomes true.

(A == B) is not true.

!= Checks if the value of two operands are equal ornot, if values are not equal then condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less thanthe value of right operand, if yes then condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= Checks if the value of left operand is less thanor equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

To understand these operators in better way you can Try it yourself.

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 zero then then condition becomes true.

(A && B) is true.

|| Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. Use to reverses thelogical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

To understand these operators in better way you can Try it yourself.

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 bit of its integerarguments.

(A & B) is 2 .

| Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments.

(A | B) is 3.

^ Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.

(A ^ B) is 1.

~ Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand.

(~B) is -4 .

<< Called Bitwise Shift Left Operator. It moves allbits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.

(A << 1) is 4.

>> Called Bitwise Shift Right with Sign Operator. It moves all bits in its first 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

(A >> 1) is 1.

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 (discardingthe 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 >> operator, except that the bits shifted in on the left are always zero,

(A >>> 1) is 1.

To understand these operators in better way you can Try it yourself.

The Assignment Operators:There are following assignment operators supported by JavaScript language:

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assigne value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands and assign the resultto left operand

C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

JavaScript if...else StatementsWhile writing a program, there may be a situation when you need to adopt one path out ofthe given two paths. So you need to make use of conditional statements that allow yourprogram to make correct decisions and perform right actions.

JavaScript supports conditional statements which are used to perform different actionsbased 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 makedecisions 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) areexecuted. If expression is false then no statement would be not executed. Most of the times youwill use comparison operators while making decisions.

Example:

<script type="text/javascript"><!--var age = 20;if( age > 18 ){ document.write("<b>Qualifies for driving</b>");}//--></script>

This will produce following result:

Qualifies for driving

To understand it in better way you can Try it yourself.

if...else statement:The if...else statement is the next form of control statement that allows JavaScript toexecute statements in more controlled way.

Syntax:

if (expression){ Statement(s) to be executed if expression is true}else{ Statement(s) to be executed if expression is false}

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) inthe ifblock, are executed. If expression is false then given statement(s) in the else block, areexecuted.

Example:

<script type="text/javascript"><!--var age = 15;if( age > 18 ){ document.write("<b>Qualifies for driving</b>");}else{ document.write("<b>Does not qualify for driving</b>");}//--></script>

This will produce following result:

Does not qualify for driving

To understand it in better way you can Try it yourself.

if...else if... statement:The if...else if... statement is the one level advance form of control statement thatallows JavaScript to make correct decision out of several conditions.

Syntax:

if (expression 1){ Statement(s) to be executed if expression 1 is true}else if (expression 2){ Statement(s) to be executed if expression 2 is true}else if (expression 3){ Statement(s) to be executed if expression 3 is true}else{ Statement(s) to be executed if no expression is true}

There is nothing special about this code. It is just a series of if statements, whereeach if is part of the else clause of the previous statement. Statement(s) are executed basedon the true condition, if non of the condition is true then else block is executed.

Example:

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

This will produce following result:

Maths Book

To understand it in better way you can Try it yourself.

JavaScript Switch CaseYou can use multiple if...else if statements, as in the previous chapter, to perform a multiwaybranch. However, this is not always the best solution, especially when all of the branchesdepend on the value of a single variable.

Starting with JavaScript 1.2, you can use a switch statement which handles exactly thissituation, 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 severaldifferent statements to execute based on the value of the expression. The interpreterchecks eachcase against the value of the expression until a match is found. If nothingmatches, a defaultcondition 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 theywere omitted, the interpreter would continue executing each statement in each of thefollowing cases.

We will explain break statement in Loop Control chapter.

Example:

Following example illustrates a basic while loop:

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

This will produce following result:

Entering switch blockGood jobExiting switch block

To understand it in better way you can Try it yourself.

Example:

Consider a case if you do not use break statement:

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

This will produce following result:

Entering switch blockGood jobPretty goodPassedNot so goodFailedUnknown gradeExiting switch block

To understand it in better way you can Try it yourself.

JavaScript while LoopsWhile writing a program, there may be a situation when you need to perform some action overand over again. In such situation you would need to write loop statements to reduce thenumber of lines.

JavaScript supports all the necessary loops to help you on all steps of programming.

The while LoopThe most basic loop in JavaScript is the while loop which would be discussed in thistutorial.

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 longasexpression is true. Once expression becomes false, the loop will be exited.

Example:

Following example illustrates a basic while loop:

<script type="text/javascript"><!--var count = 0;document.write("Starting Loop" + "<br />");while (count < 10){ document.write("Current Count : " + count + "<br />"); count++;}document.write("Loop stopped!");//--></script>

This will produce following result:

Starting LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped!

To understand it in better way you can Try it yourself.

The do...while Loop:The do...while loop is similar to the while loop except that the condition check happens atthe end of the loop. This means that the loop will always be executed at least once, evenif the condition is false.

Syntax:

do{ Statement(s) to be executed;} while (expression);

Note the semicolon used at the end of the do...while loop.

Example:

Let us write above example in terms of do...while loop.

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

This will produce following result:

Starting LoopCurrent Count : 0Loop stopped!

JavaScript for LoopsWe have seen different variants of while loop. This chapter will explain another popularloop called for loop.

The for LoopThe for loop is the most compact form of looping and includes the following three importantparts:

The loop initialization where we initialize our counter to a starting value. Theinitialization statement is executed before the loop begins.

The test statement which will test if the given condition is true or not. Ifcondition is true then code given inside the loop will be executed otherwise loopwill come out.

The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by a semicolon.

Syntax:

for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true}

Example:

Following example illustrates a basic for loop:

<script type="text/javascript"><!--var count;document.write("Starting Loop" + "<br />");for(count = 0; count < 10; count++){ document.write("Current Count : " + count ); document.write("<br />");}document.write("Loop stopped!");//--></script>

This will produce following result which is similar to while loop:

Starting LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped!

To understand it in better way you can Try it yourself.

JavaScript for...in loopThere is one more loop supported by JavaScript. It is called for...in loop. This loop isused 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 loopvery useful.

Syntax:

for (variablename in object){ statement or block to execute}

In each iteration one property from object is assigned to variablename and this loop continuestill all the properties of the object are exhausted.

Example:

Here is the following example that prints out the properties of a Webbrowser's Navigator object:

<script type="text/javascript"><!--var aProperty;document.write("Navigator Object Properties<br /> ");for (aProperty in navigator){ document.write(aProperty); document.write("<br />");}document.write("Exiting from the loop!");//--></script>

This will produce following result:

Navigator Object PropertiesappCodeNameappNameappMinorVersioncpuClassplatformpluginsopsProfileuserProfilesystemLanguageuserLanguageappVersionuserAgentonLinecookieEnabledmimeTypes

Exiting from the loop!

To understand it in better way you can Try it yourself.

Javascript - The Boolean Object

Syntax:Creating a boolean object:

var val = new Boolean(value);

If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string(""), the object has an initial value of false.

Boolean Properties:Here is a list of each property and their description.

Property Description

constructor Returns a reference to the Boolean function that created the object.

prototype The prototype property allows you to add properties and methods to an object.

Boolean MethodsHere is a list of each method and its description.

Method Description

toSource() Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.

toString() Returns a string of either "true" or "false" depending upon the value of the object.

valueOf() Returns the primitive value of the Boolean object.

Javascript - The Number ObjectThe Number object represents numerical date, either integers or floating-point numbers. Ingeneral, you do not need to worry about Number objects because the browser automaticallyconverts number literals to instances of the number class.

Syntax:

Creating a number object:

var val = new Number(number);

If the argument cannot be converted into a number, it returns NaN (Not-a-Number).

Number Properties:Here is a list of each property and its description.

Property Description

MAX_VALUE The largest possible value a number in JavaScript can have 1.7976931348623157E+308

MIN_VALUE The smallest possible value a number in JavaScript can have 5E-324

NaN Equal to a value that is not a number.

NEGATIVE_INFINITY A value that is less than MIN_VALUE.

POSITIVE_INFINITY A value that is greater than MAX_VALUE

prototype A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document

Number MethodsThe Number object contains only the default methods that are part of every object'sdefinition.

Method Description

constructor() Returns the function that created this object's instance. By default this is the Number object.

toExponential() Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.

toFixed() Formats a number with a specific number of digits to the right of the decimal.

toLocaleString() Returns a string value version of the current number in a format that may vary according to a browser's locale settings.

toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to display of a number.

toString() Returns the string representation of the number's value.

valueOf() Returns the number's value.

Javascript - The String ObjectThe String object let's you work with a series of characters and wraps Javascript's stringprimitive data type with a number of helper methods.

Because Javascript automatically converts between string primitives and String objects, youcan call any of the helper methods of the String object on a string primitive.

Syntax:Creating a String object:

var val = new String(string);

The string parameter is series of characters that has been properly encoded.

String Properties:Here is a list of each property and their description.

Property Description

constructor Returns a reference to the String function that created the object.

length Returns the length of the string.

prototype The prototype property allows you to add properties and methods to an object.

String MethodsHere is a list of each method and its description.

Method Description

charAt() Returns the character at the specified index.

charCodeAt() Returns a number indicating the Unicode value of the character at the given index.

concat() Combines the text of two strings and returns a new string.

indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

match() Used to match a regular expression against a string.

replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

search() Executes the search for a match between a regular expression and a specified string.

slice() Extracts a section of a string and returns a new string.

split() Splits a String object into an array of strings by separating the string into substrings.

substr() Returns the characters in a string beginning at the specified location through the specified number of characters.

substring() Returns the characters in a string between two indexes into the string.

toLocaleLowerCase()

The characters within a string are converted to lower case while respecting the current locale.

toLocaleUpperCase()

The characters within a string are converted to upper case while respecting the current locale.

toLowerCase() Returns the calling string value converted to lower case.

toString() Returns a string representing the specified object.

toUpperCase() Returns the calling string value converted to uppercase.

valueOf() Returns the primitive value of the specified object.

String HTML wrappersHere is a list of each method which returns a copy of the string wrapped inside theappropriate HTML tag.

Method Description

anchor() Creates an HTML anchor that is used as a hypertext target.

big() Creates a string to be displayed in a big font as if it were in a <big>tag.

blink() Creates a string to blink as if it were in a <blink> tag.

bold() Creates a string to be displayed as bold as if it were in a <b> tag.

fixed() Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag

fontcolor() Causes a string to be displayed in the specified color as if it were ina <font color="color"> tag.

fontsize() Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.

italics() Causes a string to be italic, as if it were in an <i> tag.

link() Creates an HTML hypertext link that requests another URL.

small() Causes a string to be displayed in a small font, as if it were in a <small> tag.

strike() Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.

sub() Causes a string to be displayed as a subscript, as if it were in a <sub> tag

sup() Causes a string to be displayed as a superscript, as if it were in a <sup> tag

Javascript - The Arrays ObjectThe Array object let's you store multiple values in a single variable.

Syntax:Creating a Array object:

var fruits = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a single numericparameter with the Array constructor, you specify the initial length of the array. Themaximum length allowed for an array is 4,294,967,295.

You can create array by simply assigning values as follows:

var fruits = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as follows:

fruits[0] is the first element fruits[1] is the second element fruits[2] is the third element

Array Properties:Here is a list of each property and their description.

Property Description

constructor Returns a reference to the array function that created the object.

index The property represents the zero-based index of the match in the string

input This property is only present in arrays created by regular expression matches.

length Reflects the number of elements in an array.

prototype The prototype property allows you to add properties and methods to an object.

Array MethodsHere is a list of each method and its 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 tothe 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 thelast, 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.

some() Returns true if at least one element in this array satisfies the provided testing function.

toSource() Represents the source code of an object

sort() Sorts the elements of an array.

splice() Adds and/or removes elements from an array.

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

JavaScript - The Date ObjectThe Date object is a datatype built into the JavaScript language. Date objects are createdwith thenew Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methodssimply allow you to get and set the year, month, day, hour, minute, second, and millisecondfields of the object, using either local time or UTC (universal, or GMT) time.

The ECMAScript standard requires the Date object to be able to represent any date and time,to millisecond precision, within 100 million days before or after 1/1/1970. This is a rangeof plus or minus 273,785 years, so the JavaScript is able to represent date and time tillyear 275755.

Syntax:Here are different variant of Date() constructor:

new Date( )new Date(milliseconds)new Date(datestring)new Date(year,month,date[,hour,minute,second,millisecond ])

Note: Paramters in the brackets are always optional

Here is the description of the parameters:

No Argument: With no arguments, the Date( ) constructor creates a Date object set tothe current date and time.

milliseconds: When one numeric argument is passed, it is taken as the internalnumeric representation of the date in milliseconds, as returned by the getTime( )method. For example, passing the argument 5000 creates a date that represents fiveseconds past midnight on 1/1/70.

datestring:When one string argument is passed, it is a string representation of adate, in the format accepted by the Date.parse( ) method.

7 agruments: To use the last form of constructor given above, Here is thedescription of each argument:

1. year: Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998,rather than 98.

2. month: Integer value representing the month, beginning with 0 for January to 11 for December.

3. date: Integer value representing the day of the month.4. hour: Integer value representing the hour of the day (24-hour scale).5. minute: Integer value representing the minute segment of a time reading.6. second: Integer value representing the second segment of a time reading.7. millisecond: Integer value representing the millisecond segment of a time

reading.

Date Properties:Here is a list of each property and their description.

Property Description

constructor Specifies the function that creates an object's prototype.

prototype The prototype property allows you to add properties and methods to an object.

Date Methods:Here is a list of each method and its description.

Method Description

Date() Returns today's date and time

getDate() Returns the day of the month for the specified date according to local time.

getDay() Returns the day of the week for the specified date according to local time.

getFullYear() Returns the year of the specified date according to local time.

getHours() Returns the hour in the specified date according to local time.

getMilliseconds() Returns the milliseconds in the specified date according to local time.

getMinutes() Returns the minutes in the specified date according to local time.

getMonth() Returns the month in the specified date according to local time.

getSeconds() Returns the seconds in the specified date according to local time.

getTime() Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

getTimezoneOffset() Returns the time-zone offset in minutes for the current locale.

getUTCDate() Returns the day (date) of the month in the specified date according to universal time.

getUTCDay() Returns the day of the week in the specified date according touniversal time.

getUTCFullYear() Returns the year in the specified date according to universal time.

getUTCHours() Returns the hours in the specified date according to universaltime.

getUTCMilliseconds() Returns the milliseconds in the specified date according to universal time.

getUTCMinutes() Returns the minutes in the specified date according to universal time.

getUTCMonth() Returns the month in the specified date according to universaltime.

getUTCSeconds() Returns the seconds in the specified date according to universal time.

getYear() Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.

setDate() Sets the day of the month for a specified date according to local time.

setFullYear() Sets the full year for a specified date according to local time.

setHours() Sets the hours for a specified date according to local time.

setMilliseconds() Sets the milliseconds for a specified date according to local time.

setMinutes() Sets the minutes for a specified date according to local time.

setMonth() Sets the month for a specified date according to local time.

setSeconds() Sets the seconds for a specified date according to local time.

setTime() Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

setUTCDate() Sets the day of the month for a specified date according to universal time.

setUTCFullYear() Sets the full year for a specified date according to universaltime.

setUTCHours() Sets the hour for a specified date according to universal time.

setUTCMilliseconds() Sets the milliseconds for a specified date according to universal time.

setUTCMinutes() Sets the minutes for a specified date according to universal time.

setUTCMonth() Sets the month for a specified date according to universal time.

setUTCSeconds() Sets the seconds for a specified date according to universal time.

setYear() Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.

toDateString() Returns the "date" portion of the Date as a human-readable string.

toGMTString() Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.

toLocaleDateString() Returns the "date" portion of the Date as a string, using the current locale's conventions.

toLocaleFormat() Converts a date to a string, using a format string.

toLocaleString() Converts a date to a string, using the current locale's conventions.

toLocaleTimeString() Returns the "time" portion of the Date as a string, using the current locale's conventions.

toSource() Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.

toString() Returns a string representing the specified Date object.

toTimeString() Returns the "time" portion of the Date as a human-readable string.

toUTCString() Converts a date to a string, using the universal time convention.

valueOf() Returns the primitive value of a Date object.

Date Static Methods:In addition to the many instance methods listed previously, the Date object also definestwo static methods. These methods are invoked through the Date( ) constructor itself:

Method Description

Date.parse( ) Parses a string representation of a date and time and returns the internal millisecond representation of that date.

Date.UTC( ) Returns the millisecond representation of the specified UTC date and time.

HTML Tags Ordered Alphabetically

= New in HTML5.

Tag Description

<!--...--> Defines a comment

<!DOCTYPE>  Defines the document type

<a> Defines a hyperlink

<abbr> Defines an abbreviation

<acronym> Not supported in HTML5. Use <abbr> instead.Defines an acronym

<address> Defines contact information for the author/owner of a document

<applet> Not supported in HTML5. Use <object> instead.Defines an embedded applet

<area> Defines an area inside an image-map

<article> Defines an article

<aside> Defines content aside from the page content

<audio> Defines sound content

<b> Defines bold text

<base> Specifies the base URL/target for all relative URLs in a document

<basefont> Not supported in HTML5. Use CSS instead.Specifies a default color, size, and font for all text in a document

<bdi> Isolates a part of text that might be formatted in a different directionfrom other text outside it

<bdo> Overrides the current text direction

<big> Not supported in HTML5. Use CSS instead.Defines big text

<blockquote> Defines a section that is quoted from another source

<body> Defines the document's body

<br> Defines a single line break

<button> Defines a clickable button

<canvas> Used to draw graphics, on the fly, via scripting (usually JavaScript)

<caption> Defines a table caption

<center> Not supported in HTML5. Use CSS instead.Defines centered text

<cite> Defines the title of a work

<code> Defines a piece of computer code

<col> Specifies column properties for each column within a <colgroup> element

<colgroup> Specifies a group of one or more columns in a table for formatting

<datalist> Specifies a list of pre-defined options for input controls

<dd> Defines a description/value of a term in a description list

<del> Defines text that has been deleted from a document

<details> Defines additional details that the user can view or hide

<dfn> Defines a definition term

<dialog> Defines a dialog box or window

<dir> Not supported in HTML5. Use <ul> instead.Defines a directory list

<div> Defines a section in a document

<dl> Defines a description list

<dt> Defines a term/name in a description list

<em> Defines emphasized text 

<embed> Defines a container for an external (non-HTML) application

<fieldset> Groups related elements in a form

<figcaption> Defines a caption for a <figure> element

<figure> Specifies self-contained content

<font> Not supported in HTML5. Use CSS instead.Defines font, color, and size for text

<footer> Defines a footer for a document or section

<form> Defines an HTML form for user input

<frame> Not supported in HTML5.

Defines a window (a frame) in a frameset

<frameset> Not supported in HTML5.Defines a set of frames

<h1> to <h6> Defines HTML headings

<head> Defines information about the document

<header> Defines a header for a document or section

<hr> Defines a thematic change in the content

<html> Defines the root of an HTML document

<i> Defines a part of text in an alternate voice or mood

<iframe> Defines an inline frame

<img> Defines an image

<input> Defines an input control

<ins> Defines a text that has been inserted into a document

<kbd> Defines keyboard input

<keygen> Defines a key-pair generator field (for forms)

<label> Defines a label for an <input> element

<legend> Defines a caption for a <fieldset> element

<li> Defines a list item

<link> Defines the relationship between a document and an external resource (most used to link to style sheets)

<main> Specifies the main content of a document

<map> Defines a client-side image-map

<mark> Defines marked/highlighted text

<menu> Defines a list/menu of commands

<menuitem> Defines a command/menu item that the user can invoke from a popup menu

<meta> Defines metadata about an HTML document

<meter> Defines a scalar measurement within a known range (a gauge)

<nav> Defines navigation links

<noframes> Not supported in HTML5.Defines an alternate content for users that do not support frames

<noscript> Defines an alternate content for users that do not support client-side scripts

<object> Defines an embedded object

<ol> Defines an ordered list

<optgroup> Defines a group of related options in a drop-down list

<option> Defines an option in a drop-down list

<output> Defines the result of a calculation

<p> Defines a paragraph

<param> Defines a parameter for an object

<pre> Defines preformatted text

<progress> Represents the progress of a task

<q> Defines a short quotation

<rp> Defines what to show in browsers that do not support ruby annotations

<rt> Defines an explanation/pronunciation of characters (for East Asian typography)

<ruby> Defines a ruby annotation (for East Asian typography)

<s> Defines text that is no longer correct

<samp> Defines sample output from a computer program

<script> Defines a client-side script

<section> Defines a section in a document

<select> Defines a drop-down list

<small> Defines smaller text

<source> Defines multiple media resources for media elements (<video> and <audio>)

<span> Defines a section in a document

<strike> Not supported in HTML5. Use <del> instead.Defines strikethrough text

<strong> Defines important text

<style> Defines style information for a document

<sub> Defines subscripted text

<summary> Defines a visible heading for a <details> element

<sup> Defines superscripted text

<table> Defines a table

<tbody> Groups the body content in a table

<td> Defines a cell in a table

<textarea> Defines a multiline input control (text area)

<tfoot> Groups the footer content in a table

<th> Defines a header cell in a table

<thead> Groups the header content in a table

<time> Defines a date/time

<title> Defines a title for the document

<tr> Defines a row in a table

<track> Defines text tracks for media elements (<video> and <audio>)

<tt> Not supported in HTML5. Use CSS instead.Defines teletype text

<u> Defines text that should be stylistically different from normal text

<ul> Defines an unordered list

<var> Defines a variable

<video> Defines a video or movie

<wbr> Defines a possible line-break

HTML Elements

An HTML element is everything from the start tag to the end tag:

Start tag Element content End tag

<p> This is a paragraph </p>

<a href="default.htm"> This is a link </a>

<br>    

HTML Color Names« Previous

Next Chapter »

Colors are displayed combining RED, GREEN, and BLUE light.

140 Color Names are Supported by All Browsers

140 color names are defined in the HTML5 and CSS3 color specifications.

17 colors are from the HTML specification, 123 colors are from the CSS specification.

The table below lists them all, along with their hexadecimal values.

The 17 colors from the HTML specification are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow.

Sorted by Color Name

Colors sorted by HEX values

Click on a color name (or a hex value) to view the color as the background-color along with different text colors:

Color Name HEX Color Shades

AliceBlue  #F0F8FF   Shades

AntiqueWhite  #FAEBD7   Shades

Aqua  #00FFFF   Shades

Aquamarine  #7FFFD4   Shades

Azure  #F0FFFF   Shades

Beige  #F5F5DC   Shades

Bisque  #FFE4C4   Shades

Black  #000000   Shades

BlanchedAlmond  #FFEBCD   Shades

Blue  #0000FF   Shades

BlueViolet  #8A2BE2   Shades

Brown  #A52A2A   Shades

BurlyWood  #DEB887   Shades

CadetBlue  #5F9EA0   Shades

Chartreuse  #7FFF00   Shades

Chocolate  #D2691E   Shades

Coral  #FF7F50   Shades

CornflowerBlue  #6495ED   Shades

Cornsilk  #FFF8DC   Shades

Crimson  #DC143C   Shades

Cyan  #00FFFF   Shades

DarkBlue  #00008B   Shades

DarkCyan  #008B8B   Shades

DarkGoldenRod  #B8860B   Shades

DarkGray  #A9A9A9   Shades

DarkGreen  #006400   Shades

DarkKhaki  #BDB76B   Shades

DarkMagenta  #8B008B   Shades

DarkOliveGreen  #556B2F   Shades

DarkOrange  #FF8C00   Shades

DarkOrchid  #9932CC   Shades

DarkRed  #8B0000   Shades

DarkSalmon  #E9967A   Shades

DarkSeaGreen  #8FBC8F   Shades

DarkSlateBlue  #483D8B   Shades

DarkSlateGray  #2F4F4F   Shades

DarkTurquoise  #00CED1   Shades

DarkViolet  #9400D3   Shades

DeepPink  #FF1493   Shades

DeepSkyBlue  #00BFFF   Shades

DimGray  #696969   Shades

DodgerBlue  #1E90FF   Shades

FireBrick  #B22222   Shades

FloralWhite  #FFFAF0   Shades

ForestGreen  #228B22   Shades

Fuchsia  #FF00FF   Shades

Gainsboro  #DCDCDC   Shades

GhostWhite  #F8F8FF   Shades

Gold  #FFD700   Shades

GoldenRod  #DAA520   Shades

Gray  #808080   Shades

Green  #008000   Shades

GreenYellow  #ADFF2F   Shades

HoneyDew  #F0FFF0   Shades

HotPink  #FF69B4   Shades

IndianRed     #CD5C5C   Shades

Indigo     #4B0082   Shades

Ivory  #FFFFF0   Shades

Khaki  #F0E68C   Shades

Lavender  #E6E6FA   Shades

LavenderBlush  #FFF0F5   Shades

LawnGreen  #7CFC00   Shades

LemonChiffon  #FFFACD   Shades

LightBlue  #ADD8E6   Shades

LightCoral  #F08080   Shades

LightCyan  #E0FFFF   Shades

LightGoldenRodYellow  #FAFAD2   Shades

LightGray  #D3D3D3   Shades

LightGreen  #90EE90   Shades

LightPink  #FFB6C1   Shades

LightSalmon  #FFA07A   Shades

LightSeaGreen  #20B2AA   Shades

LightSkyBlue  #87CEFA   Shades

LightSlateGray  #778899   Shades

LightSteelBlue  #B0C4DE   Shades

LightYellow  #FFFFE0   Shades

Lime  #00FF00   Shades

LimeGreen  #32CD32   Shades

Linen  #FAF0E6   Shades

Magenta  #FF00FF   Shades

Maroon  #800000   Shades

MediumAquaMarine  #66CDAA   Shades

MediumBlue  #0000CD   Shades

MediumOrchid  #BA55D3   Shades

MediumPurple  #9370DB   Shades

MediumSeaGreen  #3CB371   Shades

MediumSlateBlue  #7B68EE   Shades

MediumSpringGreen  #00FA9A   Shades

MediumTurquoise  #48D1CC   Shades

MediumVioletRed  #C71585   Shades

MidnightBlue  #191970   Shades

MintCream  #F5FFFA   Shades

MistyRose  #FFE4E1   Shades

Moccasin  #FFE4B5   Shades

NavajoWhite  #FFDEAD   Shades

Navy  #000080   Shades

OldLace  #FDF5E6   Shades

Olive  #808000   Shades

OliveDrab  #6B8E23   Shades

Orange  #FFA500   Shades

OrangeRed  #FF4500   Shades

Orchid  #DA70D6   Shades

PaleGoldenRod  #EEE8AA   Shades

PaleGreen  #98FB98   Shades

PaleTurquoise  #AFEEEE   Shades

PaleVioletRed  #DB7093   Shades

PapayaWhip  #FFEFD5   Shades

PeachPuff  #FFDAB9   Shades

Peru  #CD853F   Shades

Pink  #FFC0CB   Shades

Plum  #DDA0DD   Shades

PowderBlue  #B0E0E6   Shades

Purple  #800080   Shades

Red  #FF0000   Shades

RosyBrown  #BC8F8F   Shades

RoyalBlue  #4169E1   Shades

SaddleBrown  #8B4513   Shades

Salmon  #FA8072   Shades

SandyBrown  #F4A460   Shades

SeaGreen  #2E8B57   Shades

SeaShell  #FFF5EE   Shades

Sienna  #A0522D   Shades

Silver  #C0C0C0   Shades

SkyBlue  #87CEEB   Shades

SlateBlue  #6A5ACD   Shades

SlateGray  #708090   Shades

Snow  #FFFAFA   Shades

SpringGreen  #00FF7F   Shades

SteelBlue  #4682B4   Shades

Tan  #D2B48C   Shades

Teal  #008080   Shades

Thistle  #D8BFD8   Shades

Tomato  #FF6347   Shades

Turquoise  #40E0D0   Shades

Violet  #EE82EE   Shades

Wheat  #F5DEB3   Shades

White  #FFFFFF   Shades

WhiteSmoke  #F5F5F5   Shades

Yellow  #FFFF00   Shades

YellowGreen  #9ACD32   Shades

HTML Color Shades« Previous

Next Chapter »

Colors are displayed combining RED, GREEN, and BLUE light.

Shades of Gray

Gray colors are displayed using an equal amount of power to all of the light sources.

To make it easy for you to select a gray color we have compiled a table ofgray shades for you:

Gray Shades HEX RGB

  #000000  rgb(0,0,0) 

  #080808  rgb(8,8,8) 

  #101010  rgb(16,16,16) 

  #181818  rgb(24,24,24) 

  #202020  rgb(32,32,32) 

  #282828  rgb(40,40,40) 

  #303030  rgb(48,48,48) 

  #383838  rgb(56,56,56) 

  #404040  rgb(64,64,64) 

  #484848  rgb(72,72,72) 

  #505050  rgb(80,80,80) 

  #585858  rgb(88,88,88) 

  #606060  rgb(96,96,96) 

  #686868  rgb(104,104,104) 

  #707070  rgb(112,112,112) 

  #787878  rgb(120,120,120) 

  #808080  rgb(128,128,128) 

  #888888  rgb(136,136,136) 

  #909090  rgb(144,144,144) 

  #989898  rgb(152,152,152) 

  #A0A0A0  rgb(160,160,160) 

  #A8A8A8  rgb(168,168,168) 

  #B0B0B0  rgb(176,176,176) 

  #B8B8B8  rgb(184,184,184) 

  #C0C0C0  rgb(192,192,192) 

  #C8C8C8  rgb(200,200,200) 

  #D0D0D0  rgb(208,208,208) 

  #D8D8D8  rgb(216,216,216) 

  #E0E0E0  rgb(224,224,224) 

  #E8E8E8  rgb(232,232,232) 

  #F0F0F0  rgb(240,240,240) 

  #F8F8F8  rgb(248,248,248) 

  #FFFFFF  rgb(255,255,255) 

16 Million Different Colors

The combination of Red, Green and Blue values from 0 to 255 gives a total of more than 16 million different colors to play with (256 x 256 x 256).

Most modern monitors are capable of displaying at least 16384 different colors.

If you look at the color table below, you will see the result of varying the red light from 0 to 255, while keeping the green and blue light at zero.

To see a full list of color mixes when the red light varies from 0 to 255,click on one of the hex or rgb values below.

Red Light HEX RGB

  #000000  rgb(0,0,0) 

  #080000  rgb(8,0,0) 

  #100000  rgb(16,0,0) 

  #180000  rgb(24,0,0) 

  #200000  rgb(32,0,0) 

  #280000  rgb(40,0,0) 

  #300000  rgb(48,0,0) 

  #380000  rgb(56,0,0) 

  #400000  rgb(64,0,0) 

  #480000  rgb(72,0,0) 

  #500000  rgb(80,0,0) 

  #580000  rgb(88,0,0) 

  #600000  rgb(96,0,0) 

  #680000  rgb(104,0,0) 

  #700000  rgb(112,0,0) 

  #780000  rgb(120,0,0) 

  #800000  rgb(128,0,0) 

  #880000  rgb(136,0,0) 

  #900000  rgb(144,0,0) 

  #980000  rgb(152,0,0) 

  #A00000  rgb(160,0,0) 

  #A80000  rgb(168,0,0) 

  #B00000  rgb(176,0,0) 

  #B80000  rgb(184,0,0) 

  #C00000  rgb(192,0,0) 

  #C80000  rgb(200,0,0) 

  #D00000  rgb(208,0,0) 

  #D80000  rgb(216,0,0) 

  #E00000  rgb(224,0,0) 

  #E80000  rgb(232,0,0) 

  #F00000  rgb(240,0,0) 

  #F80000  rgb(248,0,0) 

  #FF0000  rgb(255,0,0) 

In the Stone Age

In the stone age, when computers only supported 256 different colors, a list of 216 "Web Safe Colors" was suggested as a Web standard, reserving 40 fixed system colors.

This 216 cross-browser color palette was created to ensure that all computers would display colors correctly:

000000 000033 000066 000099 0000CC

003300 003333 003366 003399 0033CC

006600 006633 006666 006699 0066CC

009900 009933 009966 009999 0099CC

00CC00 00CC33 00CC66 00CC99 00CCCC

00FF00 00FF33 00FF66 00FF99 00FFCC

330000 330033 330066 330099 3300CC

333300 333333 333366 333399 3333CC

336600 336633 336666 336699 3366CC

339900 339933 339966 339999 3399CC

33CC00 33CC33 33CC66 33CC99 33CCCC

33FF00 33FF33 33FF66 33FF99 33FFCC

660000 660033 660066 660099 6600CC

663300 663333 663366 663399 6633CC

666600 666633 666666 666699 6666CC

669900 669933 669966 669999 6699CC

66CC00 66CC33 66CC66 66CC99 66CCCC

66FF00 66FF33 66FF66 66FF99 66FFCC

990000 990033 990066 990099 9900CC

993300 993333 993366 993399 9933CC

996600 996633 996666 996699 9966CC

999900 999933 999966 999999 9999CC

99CC00 99CC33 99CC66 99CC99 99CCCC

99FF00 99FF33 99FF66 99FF99 99FFCC

CC0000 CC0033 CC0066 CC0099 CC00CC

CC3300 CC3333 CC3366 CC3399 CC33CC

CC6600 CC6633 CC6666 CC6699 CC66CC

CC9900 CC9933 CC9966 CC9999 CC99CC

CCCC00 CCCC33 CCCC66 CCCC99 CCCCCC

CCFF00 CCFF33 CCFF66 CCFF99 CCFFCC

FF0000 FF0033 FF0066 FF0099 FF00CC

FF3300 FF3333 FF3366 FF3399 FF33CC

FF6600 FF6633 FF6666 FF6699 FF66CC

FF9900 FF9933 FF9966 FF9999 FF99CC

FFCC00 FFCC33 FFCC66 FFCC99 FFCCCC

FFFF00 FFFF33 FFFF66 FFFF99 FFFFCC

Iframe - Set Height and Width

The height and width attributes are used to specify the height and width of the iframe.

The attribute values are specified in pixels by default, but they can alsobe in percent (like "80%").

Example

<iframe src="demo_iframe.htm" width="200" height="200"></iframe>

Try it Yourself »

Iframe - Remove the Border

The frameborder attribute specifies whether or not to display a border around the iframe.

Set the attribute value to "0" to remove the border:

Example

<iframe src="demo_iframe.htm" frameborder="0"></iframe>

Try it Yourself »

Use iframe as a Target for a Link

An iframe can be used as the target frame for a link.

The target attribute of a link must refer to the name attribute of the iframe:

Example

<iframe src="demo_iframe.htm" name="iframe_a"></iframe><p><a href="http://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

Try it Yourself »

HTML iframe TagTag Description

<iframe> Defines an inline frame