Examples
Basic JavaScript Examples
Write to the Document with JavaScript
Change HTML elements with JavaScript
An external JavaScript
JavaScript Statements, Comments and Blocks
JavaScript statements.
JavaScript blocks.
Single line comments.
Multiple lines comments.
Single line comment to prevent execution.
Multiple lines comment to prevent execution.
JavaScript Variables
Declare a variable, assign a value to it, and display it
JavaScript Conditional If ... Else
If statement
If...else statement
Random link
Switch statement
JavaScript Popup Boxes
Alert box
Alert box with line breaks
Confirm box
Prompt box
JavaScript Functions
Call a function
Function with an argument
Function with an argument 2
Function that returns a value
Function with arguments, that returns a value
JavaScript Loops
For loop
Looping through HTML headers
While loop
Do While loop
Break a loop
Break and continue a loop
Use a for...in statement to loop through the elements of an object
JavaScript Events
Acting to the onclick event
Acting to the onmouseover event
JavaScript Error Handling
The try...catch statement
The try...catch statement with a confirm box
The onerror event
Advanced JavaScript Examples
Create a welcome cookie
Simple timing
Another simple timing
Timing event in an infinite loop
Timing event in an infinite loop - with a Stop button
A clock created with a timing event
Create a direct instance of an object
Create an object constructor
HTML DOM Events
HTML DOM Events
DOM: Indicates in which DOM Level the property was introduced.
Mouse Events
Event | Attribute | Description | DOM |
---|---|---|---|
click | onclick | The event occurs when the user clicks on an element | 2 |
dblclick | ondblclick | The event occurs when the user double-clicks on an element | 2 |
mousedown | onmousedown | The event occurs when a user presses a mouse button over an element | 2 |
mousemove | onmousemove | The event occurs when a user moves the mouse pointer over an element | 2 |
mouseover | onmouseover | The event occurs when a user mouse over an element | 2 |
mouseout | onmouseout | The event occurs when a user moves the mouse pointer out of an element | 2 |
mouseup | onmouseup | The event occurs when a user releases a mouse button over an element | 2 |
Keyboard Events
Event | Attribute | Description | DOM |
---|---|---|---|
keydown | onkeydown | The event occurs when the user is pressing a key | 2 |
keypress | onkeypress | The event occurs when the user presses a key | 2 |
keyup | onkeyup | The event occurs when the user releases a key | 2 |
Frame/Object Events
Event | Attribute | Description | DOM |
---|---|---|---|
abort | onabort | The event occurs when an image is stopped from loading before completely loaded (for <object>) | 2 |
error | onerror | The event occurs when an image does not load properly (for <object>, <body> and <frameset>) | |
load | onload | The event occurs when a document, frameset, or <object> has been loaded | 2 |
resize | onresize | The event occurs when a document view is resized | 2 |
scroll | onscroll | The event occurs when a document view is scrolled | 2 |
unload | onunload | The event occurs once a page has unloaded (for <body> and <frameset>) | 2 |
Form Events
Event | Attribute | Description | DOM |
---|---|---|---|
blur | onblur | The event occurs when a form element loses focus | 2 |
change | onchange | The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>) | 2 |
focus | onfocus | The event occurs when an element gets focus (for <label>, <input>, <select>, textarea>, and <button>) | 2 |
reset | onreset | The event occurs when a form is reset | 2 |
select | onselect | The event occurs when a user selects some text (for <input> and <textarea>) | 2 |
submit | onsubmit | The event occurs when a form is submitted | 2 |
Event Object
Constants
Constant | Description | DOM |
---|---|---|
CAPTURING_PHASE | The current event phase is the capture phase (3) | 1 |
AT_TARGET | The current event is in the target phase, i.e. it is being evaluated at the event target (1) | 2 |
BUBBLING_PHASE | The current event phase is the bubbling phase (2) | 3 |
Properties
Property | Description | DOM |
---|---|---|
bubbles | Returns whether or not an event is a bubbling event | 2 |
cancelable | Returns whether or not an event can have its default action prevented | 2 |
currentTarget | Returns the element whose event listeners triggered the event | 2 |
eventPhase | Returns which phase of the event flow is currently being evaluated | 2 |
target | Returns the element that triggered the event | 2 |
timeStamp | Returns the time (in milliseconds relative to the epoch) at which the event was created | 2 |
type | Returns the name of the event | 2 |
Methods
Method | Description | DOM |
---|---|---|
initEvent() | Specifies the event type, whether or not the event can bubble, whether or not the event's default action can be prevented | 2 |
preventDefault() | To cancel the event if it is cancelable, meaning that any default action normally taken by the implementation as a result of the event will not occur | 2 |
stopPropagation() | To prevent further propagation of an event during event flow | 2 |
EventTarget Object
Methods
Method | Description | DOM |
---|---|---|
addEventListener() | Allows the registration of event listeners on the event target (IE8 = attachEvent()) | 2 |
dispatchEvent() | Allows to send the event to the subscribed event listeners (IE8 = fireEvent()) | 2 |
removeEventListener() | Allows the removal of event listeners on the event target (IE8 = detachEvent()) | 2 |
EventListener Object
Methods
Method | Description | DOM |
---|---|---|
handleEvent() | Called whenever an event occurs of the event type for which the EventListener interface was registered | 2 |
DocumentEvent Object
Methods
Method | Description | DOM |
---|---|---|
createEvent() | 2 |
MouseEvent/KeyboardEvent Object
Properties
Property | Description | DOM |
---|---|---|
altKey | Returns whether or not the "ALT" key was pressed when an event was triggered | 2 |
button | Returns which mouse button was clicked when an event was triggered | 2 |
clientX | Returns the horizontal coordinate of the mouse pointer, relative to the current window, when an event was triggered | 2 |
clientY | Returns the vertical coordinate of the mouse pointer, relative to the current window, when an event was triggered | 2 |
ctrlKey | Returns whether or not the "CTRL" key was pressed when an event was triggered | 2 |
keyIdentifier | Returns the identifier of a key | 3 |
keyLocation | Returns the location of the key on the advice | 3 |
metaKey | Returns whether or not the "meta" key was pressed when an event was triggered | 2 |
relatedTarget | Returns the element related to the element that triggered the event | 2 |
screenX | Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered | 2 |
screenY | Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered | 2 |
shiftKey | Returns whether or not the "SHIFT" key was pressed when an event was triggered | 2 |
Methods
Method | Description | W3C |
---|---|---|
initMouseEvent() | Initializes the value of a MouseEvent object | 2 |
initKeyboardEvent() | Initializes the value of a KeyboardEvent object | 3 |
String Object
String Object Properties
Property | Description |
---|---|
constructor | Returns the function that created the String object's prototype |
length | Returns the length of a string |
prototype | Allows you to add properties and methods to an object |
String Object Methods
Method | Description |
---|---|
charAt() | Returns the character at the specified index |
charCodeAt() | Returns the Unicode of the character at the specified index |
concat() | Joins two or more strings, and returns a copy of the joined strings |
fromCharCode() | Converts Unicode values to characters |
indexOf() | Returns the position of the first found occurrence of a specified value in a string |
lastIndexOf() | Returns the position of the last found occurrence of a specified value in a string |
match() | Searches for a match between a regular expression and a string, and returns the matches |
replace() | Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring |
search() | Searches for a match between a regular expression and a string, and returns the position of the match |
slice() | Extracts a part of a string and returns a new string |
split() | Splits a string into an array of substrings |
substr() | Extracts the characters from a string, beginning at a specified start position, and through the specified number of character |
substring() | Extracts the characters from a string, between two specified indices |
toLowerCase() | Converts a string to lowercase letters |
toUpperCase() | Converts a string to uppercase letters |
valueOf() | Returns the primitive value of a String object |
String HTML Wrapper Methods
The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.
Method | Description |
---|---|
anchor() | Creates an anchor |
big() | Displays a string using a big font |
blink() | Displays a blinking string |
bold() | Displays a string in bold |
fixed() | Displays a string using a fixed-pitch font |
fontcolor() | Displays a string using a specified color |
fontsize() | Displays a string using a specified size |
italics() | Displays a string in italic |
link() | Displays a string as a hyperlink |
small() | Displays a string using a small font |
strike() | Displays a string with a strikethrough |
sub() | Displays a string as subscript text |
sup() | Displays a string as superscript text |
Date Object
Date Object Properties
Property | Description |
---|---|
constructor | Returns the function that created the Date object's prototype |
prototype | Allows you to add properties and methods to an object |
Date Object Methods
Method | Description |
---|---|
getDate() | Returns the day of the month (from 1-31) |
getDay() | Returns the day of the week (from 0-6) |
getFullYear() | Returns the year (four digits) |
getHours() | Returns the hour (from 0-23) |
getMilliseconds() | Returns the milliseconds (from 0-999) |
getMinutes() | Returns the minutes (from 0-59) |
getMonth() | Returns the month (from 0-11) |
getSeconds() | Returns the seconds (from 0-59) |
getTime() | Returns the number of milliseconds since midnight Jan 1, 1970 |
getTimezoneOffset() | Returns the time difference between UTC time and local time, in minutes |
getUTCDate() | Returns the day of the month, according to universal time (from 1-31) |
getUTCDay() | Returns the day of the week, according to universal time (from 0-6) |
getUTCFullYear() | Returns the year, according to universal time (four digits) |
getUTCHours() | Returns the hour, according to universal time (from 0-23) |
getUTCMilliseconds() | Returns the milliseconds, according to universal time (from 0-999) |
getUTCMinutes() | Returns the minutes, according to universal time (from 0-59) |
getUTCMonth() | Returns the month, according to universal time (from 0-11) |
getUTCSeconds() | Returns the seconds, according to universal time (from 0-59) |
getYear() | Deprecated. Use the getFullYear() method instead |
parse() | Parses a date string and returns the number of milliseconds since midnight of January 1, 1970 |
setDate() | Sets the day of the month of a date object |
setFullYear() | Sets the year (four digits) of a date object |
setHours() | Sets the hour of a date object |
setMilliseconds() | Sets the milliseconds of a date object |
setMinutes() | Set the minutes of a date object |
setMonth() | Sets the month of a date object |
setSeconds() | Sets the seconds of a date object |
setTime() | Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 |
setUTCDate() | Sets the day of the month of a date object, according to universal time |
setUTCFullYear() | Sets the year of a date object, according to universal time (four digits) |
setUTCHours() | Sets the hour of a date object, according to universal time |
setUTCMilliseconds() | Sets the milliseconds of a date object, according to universal time |
setUTCMinutes() | Set the minutes of a date object, according to universal time |
setUTCMonth() | Sets the month of a date object, according to universal time |
setUTCSeconds() | Set the seconds of a date object, according to universal time |
setYear() | Deprecated. Use the setFullYear() method instead |
toDateString() | Converts the date portion of a Date object into a readable string |
toGMTString() | Deprecated. Use the toUTCString() method instead |
toISOString() | Returns the date as a string, using the ISO standard |
toJSON() | Returns the date as a string, formated as a JSON date |
toLocaleDateString() | Returns the date portion of a Date object as a string, using locale conventions |
toLocaleTimeString() | Returns the time portion of a Date object as a string, using locale conventions |
toLocaleString() | Converts a Date object to a string, using locale conventions |
toString() | Converts a Date object to a string |
toTimeString() | Converts the time portion of a Date object to a string |
toUTCString() | Converts a Date object to a string, according to universal time |
UTC() | Returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time |
valueOf() | Returns the primitive value of a Date object |
Array Object
Array Object Properties
Property | Description |
---|---|
constructor | Returns the function that created the Array object's prototype |
length | Sets or returns the number of elements in an array |
prototype | Allows you to add properties and methods to an Array object |
Array Object Methods
Method | Description |
---|---|
concat() | Joins two or more arrays, and returns a copy of the joined arrays |
indexOf() | Search the array for an element and returns it's position |
join() | Joins all elements of an array into a string |
lastIndexOf() | Search the array for an element, starting at the end, and returns it's position |
pop() | Removes the last element of an array, and returns that element |
push() | Adds new elements to the end of an array, and returns the new length |
reverse() | Reverses the order of the elements in an array |
shift() | Removes the first element of an array, and returns that element |
slice() | Selects a part of an array, and returns the new array |
sort() | Sorts the elements of an array |
splice() | Adds/Removes elements from an array |
toString() | Converts an array to a string, and returns the result |
unshift() | Adds new elements to the beginning of an array, and returns the new length |
valueOf() | Returns the primitive value of an array |
Boolean Object
Boolean Object Properties
Property | Description |
---|---|
constructor | Returns the function that created the Boolean object's prototype |
prototype | Allows you to add properties and methods to a Boolean object |
Boolean Object Methods
Method | Description |
---|---|
toString() | Converts a Boolean value to a string, and returns the result |
valueOf() | Returns the primitive value of a Boolean object |
Math Object
Math Object Properties
Property | Description |
---|---|
E | Returns Euler's number (approx. 2.718) |
LN2 | Returns the natural logarithm of 2 (approx. 0.693) |
LN10 | Returns the natural logarithm of 10 (approx. 2.302) |
LOG2E | Returns the base-2 logarithm of E (approx. 1.442) |
LOG10E | Returns the base-10 logarithm of E (approx. 0.434) |
PI | Returns PI (approx. 3.14) |
SQRT1_2 | Returns the square root of 1/2 (approx. 0.707) |
SQRT2 | Returns the square root of 2 (approx. 1.414) |
Math Object Methods
Method | Description |
---|---|
abs(x) | Returns the absolute value of x |
acos(x) | Returns the arccosine of x, in radians |
asin(x) | Returns the arcsine of x, in radians |
atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians |
atan2(y,x) | Returns the arctangent of the quotient of its arguments |
ceil(x) | Returns x, rounded upwards to the nearest integer |
cos(x) | Returns the cosine of x (x is in radians) |
exp(x) | Returns the value of Ex |
floor(x) | Returns x, rounded downwards to the nearest integer |
log(x) | Returns the natural logarithm (base E) of x |
max(x,y,z,...,n) | Returns the number with the highest value |
min(x,y,z,...,n) | Returns the number with the lowest value |
pow(x,y) | Returns the value of x to the power of y |
random() | Returns a random number between 0 and 1 |
round(x) | Rounds x to the nearest integer |
sin(x) | Returns the sine of x (x is in radians) |
sqrt(x) | Returns the square root of x |
tan(x) | Returns the tangent of an angle |
RegExp Object
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 |
'프로그래밍 놀이터 > Web' 카테고리의 다른 글
[HTML] html multimedia 관련 태그들 (0) | 2012.10.06 |
---|---|
[Script] Regular Expression(RegExp) Tutorial ( 정규식 기초강좌 ) (0) | 2012.10.06 |
[Script] JavaScript Tutorial ( 기초강좌 ) (0) | 2012.09.26 |
[Script] $(function(){}) 와 $(document).ready(function(){}) 의 차이. (0) | 2012.09.26 |
[Script] jQuery Reference Full version. (2) | 2012.09.26 |
댓글