test server

Selasa, 14 Juni 2011

MASIH BELAJAR PART 3...

HTML5

HTML5 improves interoperability and reduces development costs by making precise rules on how to handle all HTML elements, and how to recover from errors.
Some of the new features in HTML5 are functions for embedding audio, video, graphics, client-side data storage, and interactive documents. HTML5 also contains new elements like <nav>, <header>, <footer>, and <figure>.
The HTML5 working group includes AOL, Apple, Google, IBM, Microsoft, Mozilla, Nokia, Opera, and many hundreds of other vendors.
Note: HTML5 is not a W3C recommendation yet!
To read about the HTML5 activities at W3C, please read our W3C tutorial.

Ordered Alphabetically

New : New tags 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
<address> Defines an address element
<applet> Not supported in HTML5
<area> Defines an area inside an image map
<article>New Defines an article
<aside>New Defines content aside from the page content
<audio>New Defines sound content
<b> Defines bold text
<base> Defines a base URL for all the links in a page
<basefont> Not supported in HTML5
<bdo> Defines the direction of text display
<big> Not supported in HTML5
<blockquote> Defines a long quotation
<body> Defines the body element
<br> Inserts a single line break
<button> Defines a push button
<canvas>New Defines graphics
<caption> Defines a table caption
<center> Not supported in HTML5
<cite> Defines a citation
<code> Defines computer code text
<col> Defines attributes for table columns 
<colgroup> Defines groups of table columns
<command>New Defines a command button
<datalist>New Defines a dropdown list
<dd> Defines a definition description
<del> Defines deleted text
<details>New Defines details of an element
<dfn> Defines a definition term
<dir> Not supported in HTML5
<div> Defines a section in a document
<dl> Defines a definition list
<dt> Defines a definition term
<em> Defines emphasized text 
<embed>New Defines external interactive content or plugin
<fieldset> Defines a fieldset
<figcaption>New Defines the caption of a figure element
<figure>New Defines a group of media content, and their caption
<font> Not supported in HTML5
<footer>New Defines a footer for a section or page
<form> Defines a form 
<frame> Not supported in HTML5
<frameset> Not supported in HTML5
<h1> to <h6> Defines header 1 to header 6
<head> Defines information about the document
<header>New Defines a header for a section or page
<hgroup>New Defines information about a section in a document
<hr> Defines a horizontal rule
<html> Defines an html document
<i> Defines italic text
<iframe> Defines an inline sub window (frame)
<img> Defines an image
<input> Defines an input field
<ins> Defines inserted text
<keygen>New Defines a generated key in a form
<kbd> Defines keyboard text
<label> Defines a label for a form control
<legend> Defines a title in a fieldset
<li> Defines a list item
<link> Defines a resource reference
<map> Defines an image map 
<mark>New Defines marked text
<menu> Defines a menu list
<meta> Defines meta information
<meter>New Defines measurement within a predefined range
<nav>New Defines navigation links
<noframes> Not supported in HTML5
<noscript> Defines a noscript section
<object> Defines an embedded object
<ol> Defines an ordered list
<optgroup> Defines an option group
<option> Defines an option in a drop-down list
<output>New Defines some types of output
<p> Defines a paragraph
<param> Defines a parameter for an object
<pre> Defines preformatted text
<progress>New Defines progress of a task of any kind
<q> Defines a short quotation
<rp>New Used in ruby annotations to define what to show if a browser does not support the ruby element
<rt>New Defines explanation to ruby annotations
<ruby>New Defines ruby annotations
<s> Defines text that is no longer correct
<samp> Defines sample computer code
<script> Defines a script
<section>New Defines a section
<select> Defines a selectable list
<small> Defines small text
<source>New Defines media resources
<span> Defines a section in a document
<strike> Not supported in HTML5
<strong> Defines strong text
<style> Defines a style definition
<sub> Defines subscripted text
<summary>New Defines the header of a "detail" element
<sup> Defines superscripted text
<table> Defines a table
<tbody> Defines a table body
<td> Defines a table cell
<textarea> Defines a text area
<tfoot> Defines a table footer
<th> Defines a table header
<thead> Defines a table header
<time>New Defines a date/time
<title> Defines the document title
<tr> Defines a table row
<tt> Not supported in HTML5
<u> Not supported in HTML5
<ul> Defines an unordered list
<var> Defines a variable
<video>New Defines a video
<wbr>New Defines a possible line-break
<xmp> Not supported in HTML5

HTML5 <meta> Tag

Example

Describe metadata:
<head>
<meta name="description" content="Free Web tutorials" />
<meta name="keywords" content="HTML,CSS,XML,JavaScript" />
<meta name="author" content="Ståle Refsnes" />
<meta charset="UTF-8" />
</head>

Try it yourself »

Definition and Usage

Metadata is data (information) about data.
The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable.
Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.
The <meta> tag always goes inside the head element.
The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.

Differences Between HTML 4.01 and HTML5

The scheme attribute is not supported in HTML5.
HTML5 has a new attribute, charset, which makes it easier to define charset.

Example, define charset:
HTML 4.01:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
HTML5:
<meta charset="UTF-8">

Tips and Notes

Note: The <meta> tag always goes inside the head element.
Note: Metadata is always passed as name/value pairs.
Note: One, and not more, of these attributes must be defined: charset, http-equiv, name.
Note: The content attribute MUST be defined if the name or the http-equiv attribute is defined. if none of these are defined, the content attribute CANNOT be defined.

Examples

Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript" />

Define a description of your web page:
<meta name="description" content="Free Web tutorials on HTML and CSS" />

Define the last revision of your page:
<meta name="revised" content="Kai Jim Refsnes, 13/01/2011" />

Refresh page every 5 seconds:
<meta http-equiv="refresh" content="5" />


Attributes

New : New in HTML5.
Attribute Value Description
charsetNew character encoding Specifies the character encoding for the document
content some_text Specifies the content of the meta information
http-equiv content-type
expires
refresh
set-cookie
others
Specifies an HTTP header for the information in the content attribute
name author
description
keywords
generator
others
Specifies a name for the information in the content attribute
scheme format/URI Not supported in HTML5

Global Attributes

The <meta> tag also supports the Global Attributes in HTML5.

HTML5 <details> Tag

Example

Details about the document:
<details>
<summary>Copyright 1999-2011.</summary>
<p>All pages and graphics on this web site are the property of the company Refsnes Data.</p>
</details>

Try it yourself »

Definition and Usage

The <details> tag specifies additional details or controls which can be hidden or shown on demand.
The content of the <details> tag should not be visible unless the open attribute is set.

Differences Between HTML 4.01 and HTML5

The <details> tag is new in HTML5

Tips and Notes

Tip: Use it together with the <summary> tag to make your own header for the details. The header is visible, and could show the details when the user clicks on the header.

Attributes

New : New in HTML5.
Attribute Value Description
openNew open Specifies that the details should be visible

Global Attributes

The <details> tag also supports the Global Attributes in HTML5.

Event Attributes

The <details> tag also supports the Event Attributes in HTML5.

HTML <h1> to <h6> Tags

Example

The six different HTML headings:
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

Try it yourself »

Definition and Usage

The <h1> to <h6> tags are used to define HTML headings.
<h1> defines the most important heading. <h6> defines the least important heading.

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
The <h1> to <h6> tags are supported in all major browsers.

Differences Between HTML and XHTML

NONE

Optional Attributes

DTD indicates in which HTML 4.01/XHTML 1.0 DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.
Attribute Value Description DTD
align left
center
right
justify
Deprecated. Use styles instead.
Specifies the alignment of a heading
TF


Standard Attributes

The <h1> to <h6> tags support the following standard attributes:
Attribute Value Description DTD
class classname Specifies a classname for an element STF
dir rtl
ltr
Specifies the text direction for the content in an element STF
id id Specifies a unique id for an element STF
lang language_code Specifies a language code for the content in an element STF
style style_definition Specifies an inline style for an element STF
title text Specifies extra information about an element STF
xml:lang language_code Specifies a language code for the content in an element, in XHTML documents STF
More information about Standard Attributes.

Event Attributes

The <h1> to <h6> tags support the following event attributes:
Attribute Value Description DTD
onclick script Script to be run on a mouse click STF
ondblclick script Script to be run on a mouse double-click STF
onmousedown script Script to be run when mouse button is pressed STF
onmousemove script Script to be run when mouse pointer moves STF
onmouseout script Script to be run when mouse pointer moves out of an element STF
onmouseover script Script to be run when mouse pointer moves over an element STF
onmouseup script Script to be run when mouse button is released STF
onkeydown script Script to be run when a key is pressed STF
onkeypress script Script to be run when a key is pressed and released STF
onkeyup script Script to be run when a key is released STF
More information about Event Attributes.

CSS :after Selector

Complete CSS Reference Complete CSS Reference

Example

Insert content after every <p> element:
p:after
{
content:"- Remember this";
}

Try it yourself »

Definition and Usage

The :after selector inserts content after the selected element(s).
Use the content property to specify the content to insert.

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
The :after selector is supported in all major browsers.
Note: For :after to work in IE8, a <!DOCTYPE> must be declared.

Related Pages

CSS tutorial: CSS Pseudo-elements
CSS Selector Reference: CSS :before selector

Examples

Try it Yourself - Examples


Example

Insert content after every <p> element, and style the inserted content:
p:after
{
content:"- Remember this";
background-color:yellow;
color:red;
font-weight:bold;
}

Try it yourself »

Complete CSS Reference Complete CSS Reference

CSS Reference

« Previous Next Reference »

Note W3Schools' CSS reference is tested regularly with all major browsers.
Tested: 10 April, 2011.

CSS Selectors

In CSS, selectors are patterns used to select the element(s) you want to style.
The "CSS" column indicates in which CSS version the property is defined (CSS1 or CSS2).
Selector Example Example description CSS
.class .intro Selects all elements with class="intro" 1
#id #firstname Selects the element with id="firstname" 1
* * Selects all elements 2
element p Selects all <p> elements 1
element,element div,p Selects all <div> elements and all <p> elements 1
element element div p Selects all <p> elements inside <div> elements 1
element>element div>p Selects all <p> elements where the parent is a <div> element 2
element+element div+p Selects all <p> elements that are placed immediately after <div> elements 2
[attribute] [target] Selects all elements with a target attribute 2
[attribute=value] [target=_blank] Selects all elements with target="_blank" 2
[attribute~=value] [title~=flower] Selects all elements with a title attribute containing the word "flower" 2
[attribute|=language] [lang|=en] Selects all elements with a lang attribute value starting with "en" 2
:link a:link Selects all unvisited links 1
:visited a:visited Selects all visited links 1
:active a:active Selects the active link 1
:hover a:hover Selects links on mouse over 1
:focus input:focus Selects the input element which has focus 2
:first-letter p:first-letter Selects the first letter of every <p> element 1
:first-line p:first-line Selects the first line of every <p> element 1
:first-child p:first-child Selects every <p> elements that is the first child of its parent 2
:before p:before Insert content before every <p> element 2
:after p:after Insert content after every <p> element 2
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it" 2


CSS Properties

CSS Property Groups

The "CSS" column indicates in which CSS version the property is defined (CSS1 or CSS2).

Background Properties

Property Description CSS
background Sets all the background properties in one declaration 1
background-attachment Sets whether a background image is fixed or scrolls with the rest of the page 1
background-color Sets the background color of an element 1
background-image Sets the background image for an element 1
background-position Sets the starting position of a background image 1
background-repeat Sets how a background image will be repeated 1

Border and Outline Properties

Property Description CSS
border Sets all the border properties in one declaration 1
border-bottom Sets all the bottom border properties in one declaration 1
border-bottom-color Sets the color of the bottom border
border-bottom-style Sets the style of the bottom border 1
border-bottom-width Sets the width of the bottom border 1
border-color Sets the color of the four borders 1
border-left Sets all the left border properties in one declaration 1
border-left-color Sets the color of the left border 1
border-left-style Sets the style of the left border 1
border-left-width Sets the width of the left border 1
border-right Sets all the right border properties in one declaration 1
border-right-color Sets the color of the right border 1
border-right-style Sets the style of the right border 1
border-right-width Sets the width of the right border 1
border-style Sets the style of the four borders 1
border-top Sets all the top border properties in one declaration 1
border-top-color Sets the color of the top border 1
border-top-style Sets the style of the top border 1
border-top-width Sets the width of the top border 1
border-width Sets the width of the four borders 1
outline Sets all the outline properties in one declaration 2
outline-color Sets the color of an outline 2
outline-style Sets the style of an outline 2
outline-width Sets the width of an outline 2

Dimension Properties

Property Description CSS
height Sets the height of an element 1
max-height Sets the maximum height of an element 2
max-width Sets the maximum width of an element 2
min-height Sets the minimum height of an element 2
min-width Sets the minimum width of an element 2
width Sets the width of an element 1

Font Properties

Property Description CSS
font Sets all the font properties in one declaration 1
font-family Specifies the font family for text 1
font-size Specifies the font size of text 1
font-style Specifies the font style for text 1
font-variant Specifies whether or not a text should be displayed in a small-caps font 1
font-weight Specifies the weight of a font 1

Generated Content Properties

Property Description CSS
content Used with the :before and :after pseudo-elements, to insert generated content 2
counter-increment Increments one or more counters 2
counter-reset Creates or resets one or more counters 2
quotes Sets the type of quotation marks for embedded quotations 2

List Properties

Property Description CSS
list-style Sets all the properties for a list in one declaration 1
list-style-image Specifies an image as the list-item marker 1
list-style-position Specifies if the list-item markers should appear inside or outside the content flow 1
list-style-type Specifies the type of list-item marker 1

Margin Properties

Property Description CSS
margin Sets all the margin properties in one declaration 1
margin-bottom Sets the bottom margin of an element 1
margin-left Sets the left margin of an element 1
margin-right Sets the right margin of an element 1
margin-top Sets the top margin of an element 1

Padding Properties

Property Description CSS
padding Sets all the padding properties in one declaration 1
padding-bottom Sets the bottom padding of an element 1
padding-left Sets the left padding of an element 1
padding-right Sets the right padding of an element 1
padding-top Sets the top padding of an element 1

Positioning Properties

Property Description CSS
bottom Specifies the bottom position of a positioned element 2
clear Specifies which sides of an element where other floating elements are not allowed 1
clip Clips an absolutely positioned element 2
cursor Specifies the type of cursor to be displayed 2
display Specifies the type of box an element should generate 1
float Specifies whether or not a box should float 1
left Specifies the left position of a positioned element 2
overflow
Specifies what happens if content overflows an element's box 2
position Specifies the type of positioning method used for an element (static, relative, absolute or fixed) 2
right Specifies the right position of a positioned element 2
top Specifies the top position of a positioned element 2
visibility Specifies whether or not an element is visible 2
z-index Sets the stack order of a positioned element 2

Print Properties

Property Description CSS
orphans Sets the minimum number of lines that must be left at the bottom of a page when a page break occurs inside an element 2
page-break-after Sets the page-breaking behavior after an element 2
page-break-before Sets the page-breaking behavior before an element 2
page-break-inside Sets the page-breaking behavior inside an element 2
widows Sets the minimum number of lines that must be left at the top of a page when a page break occurs inside an element 2

Table Properties

Property Description CSS
border-collapse Specifies whether or not table borders should be collapsed 2
border-spacing Specifies the distance between the borders of adjacent cells 2
caption-side Specifies the placement of a table caption 2
empty-cells Specifies whether or not to display borders and background on empty cells in a table 2
table-layout Sets the layout algorithm to be used for a table 2

Text Properties

Property Description CSS
color Sets the color of text 1
direction Specifies the text direction/writing direction 2
letter-spacing Increases or decreases the space between characters in a text 1
line-height Sets the line height 1
text-align Specifies the horizontal alignment of text 1
text-decoration Specifies the decoration added to text 1
text-indent Specifies the indentation of the first line in a text-block 1
text-shadow Specifies the shadow effect added to text 2
text-transform Controls the capitalization of text 1
unicode-bidi   2
vertical-align Sets the vertical alignment of an element 1
white-space Specifies how white-space inside an element is handled 1
word-spacing Increases or decreases the space between words in a text 1


CSS display Property

CSS Reference Complete CSS Reference

Example

Let a paragraph generate an inline box:
p.inline
{
display:inline;
}

Try it yourself »

Definition and Usage

The display property specifies the type of box an element should generate.
Default value: inline
Inherited: no
Version: CSS1
JavaScript syntax: object.style.display="inline"


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
The display property is supported in all major browsers.
Note: The values "inline-table", "run-in", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" is not supported in IE7 and earlier. IE8 requires a !DOCTYPE. IE9 supports the values.

Property Values

Value Description
none The element will generate no box at all
block The element will generate a block box (a line break before and after the element)
inline The element will generate an inline box (no line break before or after the element). This is default
inline-block The element will generate a block box, laid out as an inline box
inline-table The element will generate an inline box (like <table>, with no line break before or after)
list-item The element will generate a block box, and an inline box for the list marker
run-in The element will generate a block or inline box, depending on context
table The element will behave like a table (like <table>, with a line break before and after)
table-caption The element will behave like a table caption (like <caption>)
table-cell The element will behave like a table cell
table-column The element will behave like a table column
table-column-group The element will behave like a table column group (like <colgroup>)
table-footer-group The element will behave like a table footer row group
table-header-group The element will behave like a table header row group
table-row The element will behave like a table row
table-row-group The element will behave like a table row group
inherit Specifies that the value of the display property should be inherited from the parent element


Related Pages

CSS tutorial: CSS Classification
HTML DOM reference: display property

Examples

Try it Yourself - Examples

Using the inherit value
This example demonstrates how to use the inherit property value.

CSS Reference Complete CSS Reference





CSS3 2D Transforms

« Previous Next Chapter »

CSS3 Transforms

With CSS3 transform, we can move, scale, turn, spin, and stretch elements.
CSS3 Transforms

How Does it Work?

A transform is an effect that lets an element change shape, size and position.
You can transform your elements using 2D or 3D transformation.

Browser Support

Property Browser Support
transform




Internet Explorer 9 requires the prefix -ms-.
Firefox requires the prefix -moz-.
Chrome and Safari requires the prefix -webkit-.
Opera requires the prefix -o-.

2D Transforms

In this chapter you will learn about the 2d transform methods:
  • translate()
  • rotate()
  • scale()
  • skew()
  • matrix()
You will learn about 3D transforms in the next chapter.
Opera Safari Chrome Firefox Internet Explorer

Example

div
{
transform: rotate(30deg);
-ms-transform: rotate(30deg); /* IE 9 */
-webkit-transform: rotate(30deg); /* Safari and Chrome */
-o-transform: rotate(30deg); /* Opera */
-moz-transform: rotate(30deg); /* Firefox */
}

Try it yourself »


The translate() Method

Translate With the translate() method, the element moves from its current position, depending on the parameters given for the left (X-axis) and the top (Y-axis) position:
Opera Safari Chrome Firefox Internet Explorer

Example

div
{
transform: translate(50px,100px);
-ms-transform: translate(50px,100px); /* IE 9 */
-webkit-transform: translate(50px,100px); /* Safari and Chrome */
-o-transform: translate(50px,100px); /* Opera */
-moz-transform: translate(50px,100px); /* Firefox */
}

Try it yourself »
The value translate(50px,100px) moves the element 50 pixels from the left, and 100 pixels from the top.

The rotate() Method

Rotate With the rotate() method, the element rotates clockwise at a given degree. Negative values are allowed and rotates the element counter-clockwise.
Opera Safari Chrome Firefox Internet Explorer

Example

div
{
transform: rotate(30deg);
-ms-transform: rotate(30deg); /* IE 9 */
-webkit-transform: rotate(30deg); /* Safari and Chrome */
-o-transform: rotate(30deg); /* Opera */
-moz-transform: rotate(30deg); /* Firefox */
}

Try it yourself »
The value rotate(30deg) rotates the element clockwise 30 degrees.

The scale() Method

Scale With the scale() method, the element increases or decreases the size, depending on the parameters given for the width (X-axis) and the height (Y-axis):
Opera Safari Chrome Firefox Internet Explorer

Example

div
{
transform: scale(2,4);
-ms-transform: scale(2,4); /* IE 9 */
-webkit-transform: scale(2,4); /* Safari and Chrome */
-o-transform: scale(2,4); /* Opera */
-moz-transform: scale(2,4); /* Firefox */
}

Try it yourself »
The value scale(2,4) transforms the width to be twice its original size, and the height 4 times its original size.

The skew() Method

Skew With the skew() method, the element turns in a given angle, depending on the parameters given for the horizontal (X-axis) and the vertical (Y-axis) lines:
Opera Safari Chrome Firefox Internet Explorer

Example

div
{
transform: skew(30deg,20deg);
-ms-transform: skew(30deg,20deg); /* IE 9 */
-webkit-transform: skew(30deg,20deg); /* Safari and Chrome */
-o-transform: skew(30deg,20deg); /* Opera */
-moz-transform: skew(30deg,20deg); /* Firefox */
}

Try it yourself »
The value skew(30deg,20deg) turns the element 30 degrees around the X-axis, and 20 degrees around the Y-axis.

The matrix() Method

Rotate The matrix() method combines all of the 2D transform methods into one.
The matrix method take six parameters, containing mathematic functions, which allows you to: rotate, scale, move (translate), and skew elements.
Opera Safari Chrome Firefox Internet Explorer

Example

How to rotate a div element 30 degrees, using the matrix method:
div
{
transform:matrix(0.866,0.5,-0.5,0.866,0,0);
-ms-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* IE 9 */
-moz-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* Firefox */
-webkit-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* Safari and Chrome */
-o-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* Opera */
}

Try it yourself »


New Transform Properties

The following table lists all the transform properties:
Property Description CSS
transform Applies a 2D or 3D transformation to an element 3
transform-origin Allows you to change the position on transformed elements 3

2D Transform Methods

Function Description
matrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six values
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
translateX(n) Defines a 2D translation, moving the element along the X-axis
translateY(n) Defines a 2D translation, moving the element along the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
scaleX(n) Defines a 2D scale transformation, changing the element's width
scaleY(n) Defines a 2D scale transformation, changing the element's height
rotate(angle) Defines a 2D rotation, the angle is specified in the parameter
skew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axis
skewX(angle) Defines a 2D skew transformation along the X-axis
skewY(angle) Defines a 2D skew transformation along the Y-axis



CSS3 @font-face Rule

Before CSS3, web designers had to use fonts that were already installed on the user's computer.
With CSS3, web designers can use whatever font he/she likes.
When you have found/bought the font you wish to use, simply include the font file in the web site, and it will be downloaded automatically to the user when needed.
You will have to describe your selected font with the new CSS3 @font-face rule.
In the @font-face rule you define a name for the font, and the URL to the font file:

Example

@font-face
{
font-family: myFirstFont;
src: url('Sansation_Light.ttf'),
     url('Sansation_Light.eot') format("opentype"); /* IE */
}


Browser Support

Property Browser Support
@font-face




Internet Explorer only support fonts of type .eot (Embedded OpenType).
Firefox, Chrome, Safari, and Opera support fonts of type .ttf (True Type Fonts) and .otf (OpenType Fonts).

Using The New Font

To use the new font, add "myFirstFont" as the value of the font-family property:
Opera Safari Chrome Firefox Internet Explorer

Example

div
{
font-family:myFirstFont;
}

Try it yourself »


Using Bold Text

You must add another @font-face rule containing descriptors for bold text:
Opera Safari Chrome Firefox Internet Explorer

Example

@font-face
{
font-family: myFirstFont;
src: url('Sansation_Bold.ttf'),
     url('Sansation_Bold.eot') format("opentype"); /* IE */
font-weight:bold;
}
 

Try it yourself »
The file "Sansation_Bold.ttf" is another font file, that contains the bold characters for the Sansation font.
Browsers will use this whenever a piece of text with the font-family "myFirstFont" should render as bold.
This way you can have many @font-face rules for the same font.

CSS3 Font Descriptors

The following table lists all the font descriptors that can be defined inside the @font-face rule:
Descriptor Values Description
font-family name Required. Defines a name for the font
url URL Required. Defines the URL to the font file
font-stretch normal
condensed
ultra-condensed
extra-condensed
semi-condensed
expanded
semi-expanded
extra-expanded
ultra-expanded
Optional. Defines how the font should be stretched. Default is "normal"
font-style normal
italic
oblique
Optional. Defines how the font should be styled. Default is "normal"
font-weight normal
bold
100
200
300
400
500
600
700
800
900
Optional. Defines the boldness of the font. Default is "normal"
unicode-range unicode-range Optional. Defines the range of UNICODE characters the font supports. Default is "U+0-10FFFF"




JavaScript Timing Events

« Previous Next Chapter »

1
2
3
4
5
6
7
8
9
10
11
12
 
JavaScript can be executed in time-intervals.
This is called timing events.

JavaScript Timing Events

With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setTimeout() - executes a code some time in the future
  • clearTimeout() - cancels the setTimeout()
Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.

The setTimeout() Method

Syntax

var t=setTimeout("javascript statement",milliseconds);
The setTimeout() method returns a value. In the syntax defined above, the value is stored in a variable called t. If you want to cancel the setTimeout() function, you can refer to it using the variable name.
The first parameter of setTimeout() can be a string of executable code, or a call to a function.
The second parameter indicates how many milliseconds from now you want to execute the first parameter.
Note: There are 1000 milliseconds in one second.

Example

When the button is clicked in the example below, an alert box will be displayed after 3 seconds.

Example

<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var t=setTimeout("alertMsg()",3000);
}
function alertMsg()
{
alert("Hello");
}
</script>
</head>

<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>

Try it yourself »

Example - Infinite Loop

To get a timer to work in an infinite loop, we must write a function that calls itself.
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers, if the button is pressed more than once:

Example

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Try it yourself »


The clearTimeout() Method

Syntax

clearTimeout(setTimeout_variable)

Example

The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer:

Example

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onclick="stopCount()">
</form>
</body>
</html>

Try it yourself »


Examples

More Examples

Another simple timing
A clock created with a timing event

JavaScript Browser Detection

« Previous Next Chapter »

The Navigator object contains information about the visitor's browser.

Browser Detection

Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that just don't work on certain browsers - especially on older browsers.
Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information.
The Navigator object contains information about the visitor's browser name, version, and more.
Note Note: There is no public standard that applies to the navigator object, but all major browsers support it.

The Navigator Object

The Navigator object contains all information about the visitor's browser:

Example

<div id="example"></div>

<script type="text/javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

Try it yourself »



Window setInterval() Method

Window Object Reference Window Object

Definition and Usage

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
Tip: 1000 ms = 1 second.

Syntax

setInterval(code,millisec,lang)

Parameter Description
code Required. A reference to the function or the code to be executed
millisec Required. The intervals (in milliseconds) on how often to execute the code
lang Optional. JScript | VBScript | JavaScript


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
The setInterval() method is supported in all major browsers.

Example

Example

Call the clock() function every 1000 millisecond. The clock() function updates the clock. The example also have a button to stop the clock:
<html>
<body>

<input type="text" id="clock" />
<script language=javascript>
var int=self.setInterval("clock()",1000);
function clock()
  {
  var d=new Date();
  var t=d.toLocaleTimeString();
  document.getElementById("clock").value=t;
  }
</script>
</form>
<button onclick="int=window.clearInterval(int)">Stop</button>

</body>
</html>

Try it yourself »


Window Object Reference Window Object


JavaScript eval() Function

Function Reference JavaScript Global Functions

Definition and Usage

The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

Syntax

eval(string)

Parameter Description
string A JavaScript expression, variable, statement, or sequence of statements


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
The eval() function is supported in all major browsers.

Example

Example

Evaluate/Execute JavaScript code/expressions:
<script type="text/javascript">

eval("x=10;y=20;document.write(x*y)");
document.write("<br />" + eval("2+2"));
document.write("<br />" + eval(x+17));

</script>
The output of the code above will be:
200
4
27

Try it yourself »


Function Reference JavaScript Global Functions

javaScript Statements

« Previous Next Chapter »

JavaScript is a sequence of statements to be executed by the browser.

JavaScript is Case Sensitive

Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions.

JavaScript Statements

A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" to the web page:
document.write("Hello Dolly");
It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.
The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.
Note: Using semicolons makes it possible to write multiple statements on one line.

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will write a heading and two paragraphs to a web page:

Example

<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>

Try it yourself »

JavaScript Blocks

JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket {, and end with a right curly bracket }.
The purpose of a block is to make the sequence of statements execute together.
This example will write a heading and two paragraphs to a web page:

Example

<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>

Try it yourself »
The example above is not very useful. It just demonstrates the use of a block. Normally a block is used to group statements together in a function or in a condition (where a group of statements should be executed if a condition is met).
You will learn more about functions and conditions in later chapters.




JavaScript Functions

« Previous Next Chapter »

A function will be executed by an event or by a call to the function.

JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script into a function.
A function contains code that will be executed by an event or by a call to the function.
You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section.

How to Define a Function

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.


JavaScript Function Example

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>

Try it yourself »
If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the page was loaded. Now, the script is not executed before a user hits the input button. The function displaymessage() will be executed if the input button is clicked.
You will learn more about JavaScript events in the JS Events chapter.

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>

Try it yourself »


The Lifetime of JavaScript Variables

If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

Examples

More Examples

Function with a parameter
How to pass a variable to a function, and use the variable in the function.
Function that returns a value
How to let a function return a value.



javaScript Create Your Own Objects

« Previous Next Chapter »

Objects are useful to organize information.

Examples

Try it Yourself - Examples

Create a direct instance of an object
Create a template for an object

JavaScript Objects

Earlier in this tutorial we have seen that JavaScript has several built-in objects, like String, Date, Array, and more. In addition to these built-in objects, you can also create your own.
An object is just a special kind of data, with a collection of properties and methods.
Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

Properties

The syntax for accessing a property of an object is:
objName.propName
You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";

document.write(personObj.firstname);
The code above will generate the following output:
John

Methods

An object can also contain methods.
You can call a method with the following syntax:
objName.methodName()
Note: Parameters required for the method can be passed between the parentheses.
To call a method called sleep() for the personObj:
personObj.sleep();


Creating Your Own Objects

There are different ways to create a new object:
1. Create a direct instance of an object
The following code creates an new instance of an object, and adds four properties to it:
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
alternative syntax (using object literals):
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj:
personObj.eat=eat;
2. Create an object constructor
Create a function that construct objects:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.
Once you have the object constructor, you can create new instances of the object, like this:
var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");
You can also add some methods to the person object. This is also done inside the function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}
Note that methods are just functions attached to objects. Then we will have to write the newlastname() function:
function newlastname(new_lastname)
{
this.lastname=new_lastname;
}
The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").




JavaScript Boolean Object

« Previous Next Chapter »

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

Examples

Try it Yourself - Examples

Check Boolean value
Check if a Boolean object is true or false.

Complete Boolean Object Reference

For a complete reference of all the properties and methods that can be used with the Boolean object, go to our complete Boolean object reference.
The reference contains a brief description and examples of use for each property and method!

Create a Boolean Object

The Boolean object represents two values: "true" or "false".
The following code creates a Boolean object called myBoolean:
var myBoolean=new Boolean();
If the Boolean object has no initial value, or if the passed value is one of the following:
  • 0
  • -0
  • null
  • ""
  • false
  • undefined
  • NaN
the object it is set to false. For any other value it is set to true (even with the string "false")!


JavaScript For Loop

« Previous Next Chapter »

Loops execute a block of code a specified number of times, or while a specified condition is true.

JavaScript Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript, there are two different kind of loops:
  • for - loops through a block of code a specified number of times
  • while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed
}

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing statement.

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Try it yourself »


The while loop

The while loop will be explained in the next chapter.

Examples

More Examples

Looping through HTML headings
Loop through the six different HTML headings.


JavaScript For...In Statement

« Previous Next Chapter »

JavaScript For...In Statement

The for...in statement loops through the properties of an object.

Syntax

for (variable in object)
  {
  code to be executed
  }
Note: The code in the body of the for...in loop is executed once for each property.

Example

Looping through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25};

for (x in person)
{
document.write(person[x] + " ");
}

Try it yourself »





JavaScript Where To

« Previous Next Chapter »

JavaScripts can be put in the <body> and in the <head> sections of an HTML page.

JavaScript in <body>

The example below writes the current date into an existing <p> element when the page loads:

Example

<html>
<body><h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>

</body>
</html>

Try it yourself »
Note that the JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created.

JavaScript Functions and Events

JavaScripts in an HTML page will be executed when the page loads. This is not always what we want.
Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. When this is the case we can put the script inside a function.
Events are normally used in combination with functions (like calling a function when an event occurs).
You will learn more about JavaScript functions and events in later chapters.

JavaScript in <head>

The example below calls a function when a button is clicked:

Example

<html><head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

</head>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>

Try it yourself »


Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

Using an External JavaScript

JavaScript can also be placed in external files.
External JavaScript files often contain code to be used on several different web pages.
External JavaScript files have the file extension .js.
Note: External script cannot contain the <script></script> tags!
To use an external script, point to the .js file in the "src" attribute of the <script> tag:

Example

<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>

Try it yourself »
Note: Remember to place the script exactly where you normally would write the script!

JavaScript Popup Boxes

« Previous Next Chapter »

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

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>

Try it yourself »


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>

Try it yourself »


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>

Try it yourself »


Examples

More Examples

Alert box with line breaks

JavaScript compile() Method

RegExp Object Reference JavaScript RegExp Object

Definition and Usage

The compile() method is used to compile a regular expression during execution of a script.
The compile() method can also be used to change and recompile a regular expression.

Syntax

RegExpObject.compile(regexp,modifier)

Parameter Description
regexp A regular expression
modifier Specifies the type of matching. "g" for a global match, "i" for a case-insensitive match and "gi" for a global, case-insensitive match


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari
The compile() method is supported in all major browsers, except Opera.

Example

Example

Do a global search for "man" in a string, and replace it with "person". Then change the regular expression and replace either "man" or "woman" with "person", with the compile() method:
<script type="text/javascript">

var str="Every man in the world! Every woman on earth!";
var patt=/man/g;
var str2=str.replace(patt,"person");
document.write(str2+"<br />");
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2);

</script>
The output of the code above will be:
Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!

Try it yourself »


RegExp Object Reference JavaScript RegExp Object



JavaScript RegExp Object

« Previous Next Reference »

RegExp Object

A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;
  • pattern specifies the pattern of an expression
  • modifiers specify if a search should be global, case-sensitive, etc.
For a tutorial about the RegExp object, read our JavaScript RegExp Object tutorial.

Modifiers

Modifiers are used to perform case-insensitive and global searches:
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

Brackets

Brackets are used to find a range of characters:
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified

Metacharacters

Metacharacters are characters with a special meaning:
Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx

Quantifiers

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n

RegExp Object Properties

Property Description
global Specifies if the "g" modifier is set
ignoreCase Specifies if the "i" modifier is set
lastIndex The index at which to start the next match
multiline Specifies if the "m" modifier is set
source The text of the RegExp pattern

RegExp Object Methods

Method Description
compile() Compiles a regular expression
exec() Tests for a match in a string. Returns the first match
test() Tests for a match in a string. Returns true or false


JavaScript Array Object

« Previous Next Chapter »

The Array object is used to store multiple values in a single variable.

Examples

Try it Yourself - Examples

Create an array
Create an array, assign values to it, and write the values to the output.
(You can find more examples at the bottom of this page)

Complete Array Object Reference

For a complete reference of all the properties and methods that can be used with the Array object, go to our complete Array object reference.
The reference contains a brief description and examples of use for each property and method!

What is an Array?

An array is a special variable, which can hold more than one value, at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The best solution here is to use an 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.

Create an Array

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
Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab


Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel


Examples

More Examples

Join two arrays - concat()
Join three arrays - concat()
Join all elements of an array into a string - join()
Remove the last element of an array - pop()
Add new elements to the end of an array - push()
Reverse the order of the elements in an array - reverse()
Remove the first element of an array - shift()
Select elements from an array - slice()
Sort an array (alphabetically and ascending) - sort()
Sort numbers (numerically and ascending) - sort()
Sort numbers (numerically and descending) - sort()
Add an element to position 2 in an array - splice()
Convert an array to a string - toString()
Add new elements to the beginning of an array - unshift()

JavaScript Form Validation

« Previous Next Chapter »

JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:
  • has the user left required fields empty?
  • has the user entered a valid e-mail address?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?

Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it yourself »


E-mail Validation

The function below checks if the content has the general syntax of an email.
This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end:
function validateForm()
{
var x=document.forms["myForm"]["email"].value
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}
The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

Try it yourself »

JavaScript Date Object

« Previous Next Chapter »

The Date object is used to work with dates and times.

Examples

Try it Yourself - Examples

Return today's date and time
How to use the Date() method to get today's date.
getFullYear()
Use getFullYear() to get the year.
getTime()
getTime() returns the number of milliseconds since 01.01.1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
Display a clock
How to display a clock on your web page.

Complete Date Object Reference

For a complete reference of all the properties and methods that can be used with the Date object, go to our complete Date object reference.
The reference contains a brief description and examples of use for each property and method!

Create a Date Object

The Date object is used to work with dates and times.
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)


Set Dates

We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!

Compare Two Dates

The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
  {
  alert("Today is before 14th January 2100");
  }
else
  {
  alert("Today is after 14th January 2100");
  }

SVG Examples

« Previous Next Chapter »

Viewing SVG Files

All browsers support SVG files nowadays, except for Internet Explorer, which needs a plug-in. Those are available for free, as for example the Adobe SVG Viewer.

Viewing SVG Source

To view the SVG source, open the example and right-click in the example window. Select "View Source".

SVG Examples

SVG Shapes

A rectangle
A rectangle with opacity
A rectangle with opacity 2
A rectangle with rounded corners
A circle
An ellipse
Three ellipses on top of each other
Two ellipses
A line
A polygon with three sides
A polygon with four sides
A polyline
A path
A spiral

SVG Filters

A feGaussianBlur filter
Another feGaussianBlur filter
A feBlend filter
A feColorMatrix filter
A feComponentTransfer filter
A feOffset filter
feOffset, feFlood, feComposite, feMerge, and feMergeNode
A feMorphology filter
Filter 1
Filter 2
Filter 3
Filter 4
Filter 5
Filter 6

SVG Gradients

Grad linear (horizontal gradient)
Grad linear (vertical gradient)
Grad radial
Grad radial 2

SVG Misc

Add an <a> element to a rectangle. The rectangle will act as a hyperlink
Use a JavaScript to create an a element when the user clicks on a circle
Rectangle that repeatedly fade away over 5 seconds
Animate the x, y, width, and height attributes of a rectangle and change the color of the rectangle
Three rectangles that will change color
Text that will move along a motion path
Text that will move, rotate and scale along a motion path
Text that will move, rotate and scale along a motion path + a rectangle that will "grow" and change color


SVG Gaussian Blur

« Previous Next Chapter »

An SVG Filter must be defined within a <defs> tag.

Gaussian Blur

The <filter> tag is used to define an SVG filter. The <filter> tag has a required id attribute which identifies which filter will be applied to the graphic.
The <filter> tag must be nested within a <defs> tag. The <defs> tag is short for definitions and it allows definition of special elements such as filter.
Copy the following code into Notepad and save the file as "filter1.svg". Place the file in your Web directory:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">

<defs>
<filter id="Gaussian_Blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="3" />
</filter>
</defs>

<ellipse cx="200" cy="150" rx="70" ry="40"
style="fill:#ff0000;stroke:#000000;
stroke-width:2;filter:url(#Gaussian_Blur)"/>

</svg>
Code explanation:
  • The id attribute of the <filter> tag defines a unique name for the filter (the same filter can be used by many elements in the document)
  • The filter:url(#Gaussian_Blur) property is used to link an element to a filter. The # character must be used when linking to the filters id
  • The filter effect is defined with the <feGaussianBlur> tag. The fe prefix is used for all filters
  • The stdDeviation attribute of the <feGaussianBlur> tag defines the amount of the blur
  • The in="SourceGraphic" part defines that the effect is created from the whole image
View example
Another example with a different stdDeviation:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">

<defs>
<filter id="Gaussian_Blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="20"/>
</filter>
</defs>

<ellipse cx="200" cy="150" rx="70" ry="40"
style="fill:#ff0000;stroke:#000000;
stroke-width:2;filter:url(#Gaussian_Blur)"/>

</svg>
View example


SVG Gradients - Linear

« Previous Next Chapter »

An SVG Gradient must be defined within a <defs> tag.

SVG Gradients

A gradient is a smooth transition from one color to another. In addition, several color transitions can be applied to the same element.
There are two main types of gradients in SVG:
  • Linear Gradients
  • Radial Gradients

Linear Gradients

The <linearGradient> tag is used to define an SVG linear gradient.
The <linearGradient> tag must be nested within a <defs> tag. The <defs> tag is short for definitions and it allows definition of special elements such as gradients.
Linear gradients can be defined as horizontal, vertical or angular gradients:
  • Horizontal gradients are created when y1 and y2 are equal and x1 and x2 differ
  • Vertical gradients are created when x1 and x2 are equal and y1 and y2 differ
  • Angular gradients are created when x1 and x2 differ and y1 and y2 differ
Copy the following code into Notepad and save the file as "linear1.svg". Place the file in your Web directory:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">

<defs>
<linearGradient id="orange_red" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);
stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);
stop-opacity:1"/>
</linearGradient>
</defs>

<ellipse cx="200" cy="190" rx="85" ry="55"
style="fill:url(#orange_red)"/>

</svg>
Code explanation:
  • The id attribute of the <linearGradient> tag defines a unique name for the gradient
  • The fill:url(#orange_red) property links the ellipse element to the gradient
  • The x1, x2, y1,y2 attributes of the <linearGradient> tag define the starting and ending position of the gradient
  • The color range for a gradient can be composed of two or more colors. Each color is specified with a <stop> tag. The offset attribute is used to define where the gradient color begin and end
View example (Horizontal gradient)
Another example:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">

<defs>
<linearGradient id="orange_red" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0);
stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);
stop-opacity:1"/>
</linearGradient>
</defs>

<ellipse cx="200" cy="190" rx="85" ry="55"
style="fill:url(#orange_red)"/>

</svg>
View example (Vertical gradient)

PHP MySQL Insert Into

« Previous Next Chapter »

The INSERT INTO statement is used to insert new records in a table.

Insert Data Into a Database Table

The INSERT INTO statement is used to add new records to a database table.

Syntax

It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example

In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");

mysql_close($con);
?>


Insert Data From a Form Into a Database

Now we will create an HTML form that can be used to add new records to the "Persons" table.
Here is the HTML form:
<html>
<body>

<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

</body>
</html>
When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php".
The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables.
Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the "Persons" table.
Here is the "insert.php" page:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>


 

Tidak ada komentar:

Posting Komentar