<script language="javascript" type="text/javascript" src="../file.js"> </script>
print( new Date().getHours() ); print( (new Date).getHours() ); // Same as above print( (new Date()).getHours() ); // Same as above delete variable; // removes variable/object
abc=32; // this is a number print( (abc.toString()).indexOf("2") ); // now indexOf could be used print( String(abc).indexOf("2") ); // String() and Number() is a built-in function print( Number("32").toString(16) ); // Converts a string to a number, then use toString obj to convert to HEX
x = eval('document.form_name.' + strFormControl + '.value'); x = document.form_name[strFormControl].value; // Same result as above
onscroll = foo; // A single mouse scroll will call foo hundreds of times. onscroll = function() { if(thand) clearTimeout(thand); // declare thand as local to the object calling this. thand=setTimeout(function() { dv("x"+document.body.scrollTop); // just change this to foo()/function you want to call }, 500); // this is the ms delay }
var aa=2; function ScopeDemo() { var aa = bb = 0; // bb is a GLOBAL VARIABLE myfunc = function() { } // myfunc is a GLOBAL VARIABLE (Add a var at the start to make it local); this.test = function() { } // creates a method called test which is a function print(aa); // local aa: 0 print(window.aa); // global aa: 2 << How to access a global variable! } (new ScopeDemo()).test(); // Call the test function. Create an anonymous variable internally. var x = 1; for(var y=0;y<10;y++) { var x=4; // This is NOT local to the block print("local "+x); } print(x); // outputs 4 var x = 1; (function () { for(var y=0;y<10;y++) { var x=4; // This is local to the anonymous function! Use anonymous function to localize variables. print("local "+x); } })(); print(x); // outputs 1 if(y==undefined) print('true'); // NO error exception if variable is defined later! var y=1; if(typeof(xy)=='undefined') { }; // Checks if xy is declared or not ii=33; foo(); print(ii); // 33 (ii==5 is local to foo) function foo() { print(ii); // This is undefined (not 33), even if "var" is defined later. var ii; ii=5; }
if() { } else if() { } else { }: else if while(expr) { break; continue; } do { ... } while(expr); switch(n) { case 1: execute code block 1; break; case 2: execute code block 2; default: code to be exec; }
onerror=handleErr; // will call handleErr upon error function handleErr(msg,url,lineNo) { // msg is the error string. url is the url. lineNo is the lineNo. .... }; try { code; } catch(err) { code; } // err=="error message" try { code; throw "Err1"; // Throws error } catch(er) { if(er=="Err1") { code; } } // Once it enters the catch code then it will not go back anymore.
false false value null false value undefined false value 0 false value NaN false value "" false value
Modulo: % Assignment: =, +=, -=, *=, /=, >>=, <<=, >>>=, &=, |=, ^= LOGICAL: &&, ||, ! BITWISE: &, |, ^ (xor), ~, <<, >>, >>> (unsigned right shift) ==: ("2"==2) -> TRUE ===: ("2"===2) -> FALSE !=: (3 != '3') -> FALSE (the type is converted) !==: (3 !== '3') -> TRUE 0xf: Hex 07: Octal
function isff() { return(!document.selection); } // document.selection only exist in msie function rand(limit) { return( parseInt(Math.random()*10000000)%limit ); } // 0 to (limit-1) function newelement(elem, id_toadd, newid, innerhtml) { // innerhtml is optional var newe = document.createElement(elem); newe.id = newid; if(!document.getElementById(id_toadd)) eval("document."+id_toadd+".appendChild(newe)"); // just for the error message document.getElementById(id_toadd).appendChild(newe); if(innerhtml) document.getElementById(newid).innerHTML=innerhtml; // for some unknown reason, msie dont like non-div innerHTML assignments } function loop() { // infinite loop template for(var ii=cnt=0;ii<10000;ii++, cnt++) { // cnt is global var here ...code... if( <exit criteria> ) _halt(); } print(cnt); setTimeout(loop, 10); } loop();
function foo(var1,var2,...,varX) { ....; return(x); } print(foo.length); // Returns the number of arguments needed for function foo() var abc = function foo() { // Note the empty argument. You could do this if <b>arguments</b> is used. var i=<b>arguments</b>[0]; // Cannot use "for (i in arguments) { }". var j=arguments[1]; // Must check manually if arguments[n]==undefined print(arguments.length); // The number of arguments } foo(); // This is error. foo() does not exist. Only abc() exist. window.helloworld = function() { // same as "function helloworld() { }" declared in the window itself. [Greasemonkey TIP] alert('Hello world!'); gl_abc=23; // THIS IS A GLOBAL variable (without var) } parent.foo(); // Call a foo() function declared in the parent frame. Functions across frames are not visible without using "parent". parent.midframe.foo(); // Call a foo() function declared in the frame called "midframe", As long as "midframe" is called first. alert(arguments.callee.toString().match(/function (\w+)/)[1]); // displays the caller function name. // Can also be used to call an anonymous function recursively. e.g arguments.callee(args);
function foo(arg) { }; foo = function(arg) { }; var foo = new Function("arg", "...code..."); // Variable scope only inherits GLOBAL scope for new Function. This is slow bec it is parsed everytime it is called. var foo = function abc(arg) { }; // NOTE: abc() is not accessible outside the function. objx.func1 = function() { } // Valid. "function objx.func1() {" is invalid. print(fun); // OK function fun() { print("yay"); } print(fun1); // NOT OK fun1=function() { print("yay"); }
(function(msg) { alert(msg); foo=arguments.callee; // Name (and declare) an anonymous function. foo() could be called normally (global). })('yay'); // anonymous function. Nice way of making a variable local! window.setTimeout( function() { alert('Hello world!') }, 60); // anonymous function function object1() { setTimeout("foo()",1000); // ERROR bec foo() doesn't exist after 1 sec setTimeout(function() { foo(); }, 1000); // Works OK bec of closure. Thus, use anonymous function during timeout/onevents function foo() { alert('Im foo'); }; }
print navigator.appName // Browser Name print navigator.appVersion // Browser Version print navigator.userAgent // Browser useragent print navigator.cookieEnabled // Returns true if cookies are enabled print navigator.platform // platform name (Win32) print screen.availHeight // Monitor useful Height print screen.availWidth // Monitor useful Width print screen.colorDepth // Monitor color depth print screen.height // Monitor Height print screen.width // Monitor width var color1=new String("green"); print(color1 instanceof String); // returns true print(color1 instanceof Object); // returns true var color2="coral" print(color2 instanceof String); // returns false (color2 is not a String object) t_handler=setTimeout('startTime()',500); print("Done"); // Call starttime() after 500 ms, however, continue with "print("Done")" right away. clearTimeout(t_handler); // clear/stops the timeout
function makeAdder(a) { // classic closure example (Copied from https://developer.mozilla.org/en/docs/A_re-introduction_to_JavaScript#Closures) return( function(b) { return( a + b ); }); } x = makeAdder(5); // x is a function! This is a closure example bec "a" in makeAdder still exist during print below. y = makeAdder(20); // y is a function! print(x(1)); // returns 6 print(y(2)); // returns 22 function addHandler() { // This will LEAK memory bec el is caught in the closure of the anonymous function var el = document.getElementById('el'); el.onclick = function() { this.style.backgroundColor = 'red'; // "el" exist in the inner function, thus the memory leak. } } function addHandler() { // This will prevent the memory LEAK! var el = document.getElementById('el'); el.onclick = function() { this.style.backgroundColor = 'red'; } el = null; // by the time .onclick happens, el is null already! } function addHandler() { // Another solution to prevent memory LEAK! var clickHandler = function() { this.style.backgroundColor = 'red'; } // "el" doesnt exist here (function() { var el = document.getElementById('el'); el.onclick = clickHandler; })(); } function addHandler(element) { // Avoiding closure alltogether (more memory efficient). However, it's not encapsulated. element.onclick = clickHandler; } function clickHandler() { this.style.backgroundColor = 'blue'; }
// closure example glb=0; function loop(cnt) { // cnt is a local variable var vr=40; cnt++; glb++; if(cnt==50) setTimeout(foo1, 200); if(cnt==200) setTimeout(function() { print("In anonymous: cnt="+cnt+" glb="+glb+" vr="+vr); }, 200); if(cnt==1000) { print("Done: "+cnt); return; } setTimeout("loop("+cnt+")", 1); // Need to do this so that timeout threads will work. vr=50; // This value of vr is shown in foo1() and anonymous! function foo1() { print("In foo1: cnt="+cnt+" glb="+glb+" vr="+vr); } // NOTE: if foo1() is moved outside loop() then it will error bec cnt is not defined } loop(0); // Output: // In foo1: cnt=50 glb= 63 vr=50 // In anonymous: cnt=200 glb=211 vr=50 // Done: 1000
document.write("<h1>Hello World!</h1>"); // Writes the whole html text document.getElementById("desc").innerHTML=txt; // replaces the text inside the element: <p id="desc"></p> document.getElementById("myButton").disabled=true // Disable a <button> document.getElementById("tableid").appendChild(tr_elm); // Puts tr_elm (TR element) at the bottom of the tableid var newdiv = document.createElement("div"); // Creates a new element newdiv.appendChild(document.createTextNode("John")); // Creates a new text newdiv.id="newid224"; // Sets the id document.body.appendChild(newdiv); // Adds new div element in body form_element_submit.click(); // Calls the submit button of a form (type='submit' element) tbls = document.getElementsByTagName('table'); // get all tables in the document (returns an array) print(tbls[0].className); // get the class="..." for the element print(tbls[0].id); // get the id name lgin = document.getElementsByName('login'); // get all the name="..." if (lgin[0]) { lgin[0].value='username'; } if (lgin[0]) { lgin.item(0).value='username'; } // same as above. just an example. above is a cleaner way. for (i=0;i<tbls.length;i++) { } // iterate to all the found elements for (i in tbls) { DO NOT USE } // CANNOT use this bec .item, .length, .namedItem will show up document.getElementById("someID"); // returns the element object document.getElementsByTagName("p"); // returns an array of elements that are <p> document.getElementById('maindiv').getElementsByTagName("p"); // Returns all <p> under id=maindiv var elm=document.getElementById("someID") elm.firstChild. // First Child Element elm.lastChild. // Last Child Element elm.parentNode.removeChild(elm); // Remove the elm element document.documentElement // Special property, root node document.body // Special property, access to the <body> tag .nodeName // nodeName is tag_name/attribute_name/#text (text node)/#document (document node) .nodeValue // The text for text nodes, attribute value for attribute node, not available for document or element nodes. .nodeType // 1-Element, 2-Attribute, 3-Text, 8-Comment, 9-Document document.body.bgColor="yellow" // Changes the bgColor
width = window.innerWidth || document.body.offsetWidth; // ff vs msie height = window.innerHeight || document.body.offsetHeight; // ff vs msie currentTopXlocation = document.body.scrollLeft currentTopYlocation = document.body.scrollTop
|-> Element <body> -> Element <h1> -> Text "My header" Document <HTML> | -> Element <a> (attribute: href) -> Text "My link" | |-> Element <head> -> Element <title> -> Text "My Title"
<html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html>
var arr = new Array(); // Javascript Array must have ordinal (0..n) index so that all the methods will work var arr = []; // Same as "new Array()". <b>Do not use Array() as a hash!</b> var obj = {}; // New OBJECT. This could be used as hash. Same as "new Object()"; print('pop' in arr); // TRUE, because pop is a method in Array(), even if arr is empty. print('pop' in obj); // FALSE, no method/properties in new object. arr[2]=new Array(); // Need to assign "arr[1]=new Array();" as well if arr[1] is also an array. arr[2][8]=32; // Array of arrays print(arr[2][8]); var nnn=new Array(); // This allocates memory bec of the "new" nnn=arr; // Object assignment is always treated as pointers. The original allocated memory is garbage collected. arr[0]=9; print(nnn[0]); // result is 9.
grades["ab"]=value; // You are adding "ab" property to the object grades. grades.ab=value; // same as above
var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; for (var iary=mycars, item,i=0,ilen=iary.length; (item = iary[i]) || i<ilen; i++) { // Excellent way of iterating an Array. Equivalent to "foreach $item (@mycars)". Includes empty/falsy items. // Do something with item } for (x in mycars) { // equivalent to "for($x=0;$x<=$#mycars;$x++) {" as an Array context document.write(mycars[x] + "<br />"); // However, any extension to Array() will also showup (using Array.prototype). } var hh = {}; hh['fred']=95; hh['mike']=96; // Use this for simple hash (no sorting of keys, etc) for (x in hh) { // equivalent to "foreach $x (keys(%hh))" print(hh[x]); } var hh = new hash(); hh['fred']=95; hh['mike']=96; // Use this for has with builtin methods (sortkeys, etc) for (x in hh.$sortkeys()) { // equivalent to "foreach $x (sort(keys(%hh)))" print(hh[x]); }
function func(ary) { ary[0]=5; } var abc=new Array(); abc[0]=8; func(abc); print(abc[0]); // RESULT is 5
delete arr[index]; // array delete hh['key_to_delete']; // hash
if(23 in arr) { } if('methodtocheck' in obj) { } if('keytocheck' in hh) { } // This is faster compared to hh['keytocheck']==undefined if(hh.$defined('keytocheck')) { } // this is just readability. it is exactly the same as above. if(hh['aa']==undefined) { } // another way
var aa = ["a","b","c", "d"]; // 1st method var aa = new Array("a","b","c", "d"); // 2nd method var hh = new hash({a:"john",b:{"xx":"cathy","yy":"catherine"},"c":"paul"}); // Hash list constructor
for (i in document['body']['style']) { }; for (i in document.body.style) { }; Thus: hh = new hash({"a" : {"bb":"john","cc":"cathy"))); hh.a.cc === hh['a']['cc'] -> See "avoiding eval" at the basic stuff.
var line='abc3defghi'; if(line.match(/(\d+)(\w\w)/)) { print(RegExp.$1); print(RegExp.$2); } else { print("not found"); } line='the function foo()'; print(line.match(/function (\w+)/)[1]); // "foo" (shorthand notation) if("the function foo()".match(/function (\w+)/)) // Direct string test res=line.match(RegExp("function (\\w+)")); print(res[0]); // "function foo" print(res[1]); // "foo" print(res.index); // 4 print(res.input); // "the function foo()" regex=/function (\w+)/; res=regex.exec("the function foo()"); // The "confusing" notation // same result as above
if(line.match(RegExp("(\\d+)"+vr+"(\\w\\w)"))) { } // using line variable if(RegExp("(\\d+)(\\w\\w)").exec("abc3def")) { } // direct string
res=vr.replace(/(\d+)(\w+)/, "$1 $2"); res=vr.replace(RegExp("regex"), "$1 $2");
.indexOf("string_to_search") -> -1 if not found .myindexOf("string_to_search") -> 0 if not found (Could be used as bool). This is own method.
re = new RegExp("(\\d+)(\\w\\w)"); // RegExp is an object. Removing the "new" works as well. However, better use "new" when assigning. arr = re.exec("abc3defghi"); // returns the $0,$1,$2 as an array print(arr); // 3de,3,de if(re.test("abcdef")) { } // This is false
function employee(name, jobtitle, born) { this.myname=name this.jobtitle=jobtitle this.born=born var mythis=this; // This is a good trick to use during onevent calls. var var_age=10; // Default value. This variable cannot be accessed outside the object. this.setage=setagefunc; // This is not an original part of the obj, see arguments. THIS IS A FUNCTION e.g. fred.setage() this.getage=function() { // Anonymous function return(var_age+" years"); } function setagefunc(newage) { // Cannot access setagefunc from outside. However, this is equivalent to this.setage() var_age=newage; return(this.getage()); // See note on next line regarding usage of "this." inside function } //setagefunc(15); // ERROR. this.getage() does not exist inside func! However, if you use: "this.setage(15)" then it works ok. } employee.prototype.salary=1000; // Extend the object by adding a salary property. (Not inheritance) var fred=new employee("Fred Flintstone","Caveman",1970) print(fred.salary); // Output is 1000 print(fred.getage()); // 10 years print(fred.setage(40)); // 40 years print(fred.setage); // returns the function (useless) fred.setage=5; // Just for illustration. In objects, you don't reassign if it is a function. print(fred.setage); // 5 print(fred.setage(20)); // ERROR. (fred.age is not a function bec it is assigned to 5.
function obj() { this.go = function() { print("1st"); }; } v1=new abc(); v1.go(); // output is "1st" abc.prototype.go = function() { print("2nd"); }; v1.go(); // output is "1st" v2=new obj(); v2.go(); // output is "1st"
// Using the same employee object as above function employee2(name, jobtitle, born, sal) { this.salary=sal; // new property employee.call(this, name, jobtitle, born); // inherit the employee! // The above could also be written as: (however, it defines a ".base" method which could be eliminated when using .call) // this.base = employee; // this.base(name, jobtitle, born); } var fred=new employee2("Fred","Caveman",1970, 2000) print(fred.salary); // 2000 print(fred.myname); // Fred
employee.prototype.location = "Moab"; // employee is extended function employee2(name, jobtitle, born, sal) { this.salary=sal; employee.call(this, name, jobtitle, born); // inherit the employee, however, the extension is not taken. } var emp1=new employee("Paul","Engr","2005"); var emp2=new employee2("Ron","Acct","2006"); print(emp1.location); print(emp2.location); // UNDEFINED! employee does not have .location originally
print( employee ); // Prints the function contents print( fred.constructor ); // Prints the function contents (exactly as above. Infact its a pointer). // .constructor is a read only print( fred ); // Outputs "[object Object]"
.watch(property, handler_foo); // watch a property if it changes .unwatch(property); // unwatch it function handler_foo(id,oldval,newval) { } // id is the property name given var fred=new employee("Fred","Caveman",1970) fred.watch("myname", function(id,aa,bb) { print("CHANGED! "+id+" = "+aa+" -> " + bb); } ); fred.myname="new name"; // Will display "CHANGED! myname = Fred -> new name" // Cannot use employee.prototype.watch(...) // .watch can be defined inside the object using "this.watch(....)";
function myobj(arg) { var txt=arg; this.toString = function() { return("Mr "+txt); } } aa = new myobj("John"); print(aa); // .toString is implicitly called vr = aa; // vr now points to aa, .toString is NOT called vr = aa+""; // .toString is called. Do this when you are expecting a string. vr = aa-0; // .toString is called. Do this when you are expecting a number. vr = Number(aa); // same as vr=aa-0 vr = aa.toString(); // same as vr=aa+""
function employee() { ... if(employee.staticvar1==undefined) { employee.staticvar1=1; // one-time initialization } // .staticvar1 doesn't exist in the created objects ... if(this === window) { } // Determine if called as a function (this===window) or as an object (this!=window) ... // update or use employee.staticvar1 anytime here ... }
(function objx_init() { // objx_init is just a name. This is not accessible. print("One time init"); // Do one time initialization here objx = function() { // Declare the main function/object print("I'm in objx"); } objx.func1 = function() { // static function print("doing func1"); } objx(); // Call objx (if you need to). })(); objx(); objx(); objx.func1();
Javascript | Perl ========================================== ========================================= while() { break; continue; } | while() { next; last; } switch(xx) { case nn: code; default: code } | if(xx==nn) { } elsif(xx==nn2) { } else { } if(typeof(varr)!='undefined') { } | if(defined($varr)) { } | var hh={}; -no methods- | my( %hh ); for (i in hh) { } | foreach $i (keys(%hh)) { } hh['abc']='a'+3; | $hh{'abc'}='a' . 3 ; | var hh=new hash(); -with methods- | my( %hh ); for (i in hh.$keys()) { } | foreach $i (keys(%hh)) { } for (i in hh.$sortkeys()) { } | foreach $i (sort(keys(%hh)) { } if('abc' in hh) { } | if(defined($hh{'abc'})) { } if(hh['abc']!=undefined) { } | -same as above- (slower) | var arr=new Array; | my( @arr); for (var i=0,xx; xx=arr[i];i++) { } | foreach $xx (@arr) { } for (var i=0,xx; xx=(["a","b","c"])[i];i++) | foreach $xx (qw(a b c)) { } arr[0]=23; arr.push(45); | $arr[0]=23; push(@arr, 45); | if(line.match(/reg(ex)/)) { a=RegExp.$1; } | if($line=~/reg(ex)/) { $a=$1; } line=line.replace(/(reg)ex/g, "$1"); | $line=~s/(reg)ex/$1/g; if(line.match(RegExp($yy, "i"))) { } | if($line=~/$yy/i) { } |
Javascript | Perl ====================================== | ========================================= | function employee(name) | package employee; { | employee.static_var=10; | my $static_var=10; | sub new { | my ($class, $name)=@_; | my $self = {}; bless($self, $class); var mythis=this; | var var_age = 10; | $self->{var_age} = 10; # no direct equivalent for perl for local variable within object this.myname=name; | $self->{myname} = $name; print("in constructor"); | print("in constructor\n"); | return($self); | } this.setage=function(newage) { | sub setage { | my($self, $newage) = @_; var_age=newage; | $self->{var_age} = $newage; var localv; | my $localv; return(var_age); | return($self->{var_age}); } | } | function foo() { | sub foo { # no equivalent for a "private" function in perl | my($self) = @_; mythis.ary=[]; | @{$self->{ary))=(); mythis.ary.push("abc"); | push(@{$self->{ary)), "abc"); # array access return("internal function"); | return("not internal, this is part of object, Can be accessed"); } | } | } | function emp2(n,s,job) { | package emp2; # inheritance | use employee; # The source obj | @ISA = ("employee"); # inherits from Person | use strict; | .... # add the obj_args() here | sub new { | my ($class, $n, $s, $job)=@_; # 1st arg is always the classname employee.call(this, n); | my $self = new employee($n); ... | ... } | } // ========== main file | #========= var fred=new employee("Fred"); | my $fred = new employee("Fred"); print( fred.setage(30) ); | print $fred->setage(30); print( fred.myname ); | print $fred->{myname}; // Cannot be done on js | employee::foo(); # call foo directly |
test | firefox | ie | cygwin-perl |
---|---|---|---|
1000000 rand generate pure assignment |
1.4 sec | 1.2 sec | 0.37 sec |
500000 lfsr assign to hash Hash read&write |
8.1sec | 45sec | 1.9sec |
.indexof 100000 iteration | 2.2sec | 5.4sec | n/a |
.match 100000 | 19sec | 4.4sec (wow!) | n/a |
.replace 100000 | 21sec | 6.5sec (wow!) | n/a |
Function | Description |
---|---|
Boolean(val) | Converts a value to a boolean |
Date(void) | Returns the date&time in "Sun Dec 10 2006 21:28:35 GMT-0800 (Pacific Standard Time)" format. This is different from the Date object. |
decodeURI() | Decodes an encoded URI |
decodeURIComponent() | Decodes an encoded URI component |
encodeURI() | Encodes a string as a URI |
encodeURIComponent() | Encodes a string as a URI component |
Error() | Creates an Error object. Equivalent to "new Error(..)"; |
escape() | Encodes a string: ":%22 %:%25 ':%27 |
eval(string) | Evaluates a string and executes it as if it was script code |
Function(arg, [arg, ...], funcbody) | Creates a Function object (which is basically a function). e.g. var multiply = new Function("x", "y", "return x * y") |
isFinite(val) | Checks if a value is a finite number |
isNaN(val) | Checks if a value is not a number |
Number(val) | Converts an object's value to a number |
parseFloat(string) | Parses a string and returns a floating point number |
parseInt(string|number, [radix]) | Parses a string and returns an integer. Basic int() function. |
RegExp("pattern", ["flags"]) | Returns a regular expression object. See also this section |
String(val) | Converts an object's value to a string. Calls the .toString() method implicitly if val is an object. Same behavior as val+"" |
typeof(var) | Returns the type of the variable. Either "number", "string", "boolean", "object", "function", "undefined" |
unescape() | Decodes a string encoded by escape() |
Other Functions | |
alert(text) | Shows a popup window with text message. No Cancel button |
confirm(text) | Shows a popup window with OK and Cancel. Returns false if cancel is pressed. |
prompt(text, default_value) | Generates a popup window and prompts for string |
Global Constants | |
Infinity | A numeric value that represents positive or negative infinity |
NaN | A value representing Not-A-Number |
undefined | Indicates that a variable has not been assigned a value. Sometimes "null" is also used. |
Number Methods | |
.toExponential([fractiondigits]) | Returns a string representing the number in exponential notation. |
.toFixed([fractiondigit]) | Returns a string representing the number in fixed-point notation. By default fractiondigit is 0. It will do proper rounding. e.g. print((123.456).toFixed(1)); // "123.5" |
.toLocaleString | Returns a human readable string representing the number using the locale of the environment. Overrides the Object.toLocaleString method. |
.toPrecision([digits]) | Returns a string representing the number to a specified precision/digits in fixed-point notation. e.g. print((45.1).toPrecision(1)); // "5e+1" |
.toString([radix]) | Returns a string considering the given radix/base. Overrides the Object.toString method. Converts a number to hex or binary. |
.valueOf | Returns the primitive value of the specified object. Overrides the Object.valueOf method. |
Number Properties | |
Number.MAX_VALUE | The largest representable number |
Number.MIN_VALUE | The smallest representable number. |
Number.NaN | Special "not a number" value (I don't find any use for this) |
Number.NEGATIVE_INFINITY | Special value representing negative infinity; returned on overflow. |
Number.POSITIVE_INFINITY | Special value representing infinity; returned on overflow. |
eg. <body onload="message()">.... </body> // Calls javascript function message(). Declare message() in <head> <form><input type="button" onclick="disp_alert()" value="Display alert box"></form> // Button, calls disp_alert() document.getElementById('id1').onmousemove = foo; // NOTE: No arguments!! in ff, event is automatically passed as argument. In msie, need to use window.event;
Attribute | The event occurs when... |
---|---|
onload (window) | A page or an image is finished loading |
onunload (window) | The user exits the page |
onchange (form) | The content of a field changes |
onsubmit (form) | The submit button is clicked |
onreset (form) | The reset button is clicked |
onselect (form) | Text is selected |
onblur (form) | An element loses focus |
onfocus (form) | An element gets focus |
onkeydown (keyboard) | A keyboard key is pressed |
onkeypress (keyboard) | A keyboard key is pressed or held down |
onkeyup (keyboard) | A keyboard key is released |
onclick (mouse) | Mouse clicks an object |
ondblclick (mouse) | Mouse double-clicks an object (not in WINDOW.) |
onmousedown (mouse) | A mouse button is pressed |
onmousemove (mouse) | The mouse is moved |
onmouseout (mouse) | The mouse is moved off an element |
onmouseover (mouse) | The mouse is moved over an element |
onmouseup (mouse) | A mouse button is released |
onabort | Loading of an image is interrupted |
onerror | An error occurs when loading a document or an image |
onresize | A window or frame is resized |
Additional WINDOW events | (mozilla specific, not sure which are msie compatible.) |
window.onclose=func; | window close event |
window.ondragdrop=func; | drag and drop events on the window |
window.onpaint=func; | paint events on the window |
window.onscroll=func; | window scrolling (msie OK) |
leftFrame = parent.frames.leftGuy; // leftGuy is the name of the frame onscroll = keepTogether; function keepTogether(){ leftFrame.document.body.scrollTop = document.body.scrollTop; }
txt.toUpperCase() // converts to uppercase (string object)
Function | Description |
---|---|
charAt(index) | Returns the character at a specified position |
charCodeAt(index) | Returns the Unicode of the character at a specified position |
concat(str1,[str2],...) | Joins two or more strings. Joins the source object with str1 first, then returns the joined string. |
String.fromCharCode(num1,[num2],...) | Takes the specified Unicode values and returns a string. This is the chr() in BASIC. |
indexOf(str, [fromindex]) | Returns the position of the first occurrence of a specified string value in a string This is fast. Returns -1 if not found |
lastIndexOf(str, [fromindex]) | Returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string |
match(string|regex) | Searches for a specified value in a string. Returns false if not found. Returns an array of matched string ($1 is element 1). |
replace(string|regex, str) | Replaces some characters with some other characters in a string. Does not replace the source object. Returns the replaced text. If search is not found, it will return the original string. |
search(string|regex) | Regex search. Returns -1 if not found. Returns index of searched string. |
slice(start,[end]) | Extracts a part of a string and returns the extracted part in a new string |
split(string|regex, [howmany]) | Splits a string into an array of strings. Returns an ARRAY. |
substr(start,[cnt]) | Extracts a specified number of characters in a string, from a start index |
substring(start,[stop]) | Extracts the characters in a string between two specified indices |
toLowerCase(void) | Displays a string in lowercase letters |
toUpperCase(void) | Displays a string in uppercase letters |
valueOf() | Returns the primitive value of a String object (This is internally used) |
HTML/Font Related | |
anchor(anchorname) | Creates an HTML anchor |
big(void) | Displays a string in a big font |
blink(void) | Displays a blinking string (NOT IN msie) |
bold(void) | Displays a string in bold |
fixed(void) | Displays a string as teletype text |
fontcolor(color) | Displays a string in a specified color |
fontsize(size) | Displays a string in a specified size |
italics(void) | Displays a string in italic |
link(url) | Displays a string as a hyperlink e.g. var str="Go here"; print(str.link('http://abc')); // RESULT: <a href='http://abc'>Go here</a> |
small(void) | Displays a string in a small font |
strike(void) | Displays a string with a strikethrough |
sub(void) | Displays a string as subscript |
sup(void) | Displays a string as superscript |
Properties | |
length | Returns the number of characters in a string |
My own Methods | |
mycksum(void) | Returns a unique cksum/CRC sting |
myindexOf(str, [fromindex]) | Returns 0 if NOT found, index+1 if found. Could be used as boolean!String.prototype.myindexOf = function(aa, bb) { return(this.indexOf(aa,bb)+1); }; |
var d = new Date; // Date or Date() will work print(d.getHours()); print(d.getDay); // Get the date/hour print(new Date().getHours()); // Same notation var start = new Date().getTime() // same as std.getHours()*60*60*1000 + std.getMinutes()*60*1000 + std.getSeconds()*1000 + std.getMilliseconds();
Function | Description |
---|---|
Date(void) - function | Returns the current date and time e.g. print(Date()); |
Date(args) - object | Creates a Date object. The "time" of the created object is static. |
Static Methods | |
Date.parse(dateString) | Parses a dateString and returns the number of milliseconds since Jan 1, 1970, e.g. print(Date.parse("Aug 9, 1995")); |
Date.UTC(args) | Returns milliseconds. args is year, month[, date[, hrs[, min[, sec[, ms]]]]] |
Methods | |
getDate(void) | Returns the day of the month from a Date object (from 1-31) |
getDay(void) | Returns the day of the week from a Date object (from 0-6) |
getMonth(void) | Returns the month from a Date object (from 0-11) |
getFullYear(void) | Returns the year, as a four-digit number, from a Date object |
getHours(void) | Returns the hour of a Date object (from 0-23) |
getMinutes(void) | Returns the minutes of a Date object (from 0-59) |
getSeconds(void) | Returns the seconds of a Date object (from 0-59) |
getMilliseconds(void) | Returns the milliseconds of a Date object (from 0-999) |
getTime(void) | Returns the number of milliseconds since midnight Jan 1, 1970 |
getTimezoneOffset() | Returns the difference in minutes between local time and Greenwich Mean Time (GMT) |
getUTCDate() | Returns the day of the month from a Date object according to universal time (from 1-31) |
getUTCDay() | Returns the day of the week from a Date object according to universal time (from 0-6) |
getUTCMonth() | Returns the month from a Date object according to universal time (from 0-11) |
getUTCFullYear() | Returns the four-digit year from a Date object according to universal time |
getUTCHours() | Returns the hour of a Date object according to universal time (from 0-23) |
getUTCMinutes() | Returns the minutes of a Date object according to universal time (from 0-59) |
getUTCSeconds() | Returns the seconds of a Date object according to universal time (from 0-59) |
getUTCMilliseconds() | Returns the milliseconds of a Date object according to universal time (from 0-999) |
parse() | Takes a date string and returns the number of milliseconds since midnight of January 1, 1970 |
setDate() | Sets the day of the month in a Date object (from 1-31) |
setMonth() | Sets the month in a Date object (from 0-11) |
setFullYear() | Sets the year in a Date object (four digits) |
setHours() | Sets the hour in a Date object (from 0-23) |
setMinutes() | Set the minutes in a Date object (from 0-59) |
setSeconds() | Sets the seconds in a Date object (from 0-59) |
setMilliseconds() | Sets the milliseconds in a Date object (from 0-999) |
setTime() | Calculates 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 in a Date object according to universal time (from 1-31) |
setUTCMonth() | Sets the month in a Date object according to universal time (from 0-11) |
setUTCFullYear() | Sets the year in a Date object according to universal time (four digits) |
setUTCHours() | Sets the hour in a Date object according to universal time (from 0-23) |
setUTCMinutes() | Set the minutes in a Date object according to universal time (from 0-59) |
setUTCSeconds() | Set the seconds in a Date object according to universal time (from 0-59) |
setUTCMilliseconds() | Sets the milliseconds in a Date object according to universal time (from 0-999) |
toString() | Converts a Date object to a string |
toUTCString() | Converts a Date object, according to universal time, to a string |
toLocaleString() | Converts a Date object, according to local time, to a string |
UTC() | Takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time |
valueOf() | Returns the primitive value of a Date object |
Properties | |
None |
e.g. var mycars=new Array("Saab","Volvo","BMW") var mycars=["Saab","Volvo","BMW"]; var myhash=new hash({"a":"Saab","b":"Volvo","c":"BMW"});
Function | Description |
---|---|
concat(ary|value, ...) | Joins two or more arrays and returns the resulting (new) array Copies an array (if no arguments) e.g. res = arr.concat(arr2) |
join([string]) | Puts all the elements of an array into a string. The elements are separated by a specified delimiter (default is comma). e.g. print(arr.join(";")) |
pop(void) | Removes and returns the last element of an array |
push(newelement, ...) | Adds one or more elements to the end of an array and returns the new length. |
reverse(void) | Returns the reversed order of the elements. This modifies the source array. |
shift(void) | Removes and returns the first element of an array. |
slice(start,[end]) | Returns a new array, returns the selected elements |
sort([sortfunc]) | Sorts the elements of an array. This modifies the source array. Default sort is string sort.
Can only sort if array has 0..n indexes, ie, cannot sort hash. Sort routines at the bottom of this section |
splice(index,howmany, [element1],[...]) |
Removes and adds new elements to an array. Modifies the array. Returns the removed elements (new array). element1, etc are the elements that are replaced in the removed slot. |
toString(void) | Converts an array to a string and returns the result. Does not work with hash. |
unshift(newelement1, [newelement2], [...]) |
Adds one or more elements to the beginning of an array and returns the new length |
valueOf() | Returns the primitive value of an Array object. |
Properties | |
length | Sets or returns the number of elements in an array (Does not work with hash) |
hash Methods | |
$addhash(ky1,ky2,value) | Makes ky1 as a hash object. Adds ky2,value in ky1. (shortcut for hash of hash assignment) |
$concat(hash|{ }) | Adds/concats the elements of another hash/object. This will overwrite existing keys. This modifies the source. Returns itself. |
$deletelast(void) | Deletes the last added element. Returns the removed key. |
$inc(key) | Increments the value of the specified key. If value is not numeric, it will set it to 1. (Shortcut for if(!defined()) initialize; then increment;) |
$poparray(key) | Pops the last array element in the specified key. Returns the popped value. |
$pusharray(key,value) | Adds/pushes "value" as an array to the specified key. |
$defined(key) | Returns true if the key is defined. This is the same as if(key in hh). This is just for readability. |
$ishash(key) | Returns true if the key is pointing to a hash (hash of hash). |
$join([delimiter]) | Returns a string with the values joined together separated by "delimiter" |
$joinkeys([delimiter]) | Returns a string with the keys joined together separated by "delimiter" |
$keys(void) | Returns the keys as an object. Used in for (x in hh.$keys()) |
$length(void) | Returns the number of keys |
$sortkeys([sortfunc]) | Returns a new object with sorted keys. Does not modify the source. Usage: for (i in hh.$sortkeys()) print(hh[i]); |
$sortvalues([sortfunc]) | Returns a new object with sorted values. Does not modify the source. It returns the keys not the values. Usage: for (i in hh.$sortvalues()) print(hh[i]); |
$sortkeys_new([sortfunc]) | Returns a new hash with sorted keys. Does not modify the source. This could also be used to copy/duplicate a hash. Usage: hh=hh.$sortkeys_new(); // This will sort hh and replace hh. |
$sortvalues_new([sortfunc]) | Returns a new hash with sorted values. Does not modify the source. Usage: hh=hh.$sortvalues_new(); // This will sort hh and replace hh. |
$valexist(string) | Returns true if the given string exist as a value |
newarr=arr.sort() // This will sort arr and assigns newarr=arr as a pointer; // Numeric sort: (make (a,b) to (b,a) to reverse): function(a,b) { return(Number(a)-Number(b)); } // case-insensitive sort: (make (a,b) to (b,a) to reverse): function(a,b) { var aa,bb; return((aa=a.toString().toLowerCase())==(bb=b.toString().toLowerCase())?0:(aa<bb?-1:1)); } // case-sensitive sort (descending). Default sort is ascending case-sensitive. function(b,a) { var aa,bb; return((aa=a.toString())==(bb=b.toString())?0:(aa<bb?-1:1)); }
print Math.random() // Random number (Math method) print Math.floor(1.2);
Function | Description |
---|---|
abs(x) | Returns the absolute value of a number |
acos(x) | Returns the arccosine of a number |
asin(x) | Returns the arcsine of a number |
atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians |
atan2(y,x) | Returns the angle theta of an (x,y) point as a numeric value between -PI and PI radians |
ceil(x) | Returns the value of a number rounded upwards to the nearest integer |
cos(x) | Returns the cosine of a number |
exp(x) | Returns the value of Ex |
floor(x) | Returns the value of a number rounded downwards to the nearest integer |
log(x) | Returns the natural logarithm (base E) of a number |
max(x,y) | Returns the number with the highest value of x and y |
min(x,y) | Returns the number with the lowest value of x and y |
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 a number to the nearest integer |
sin(x) | Returns the sine of a number |
sqrt(x) | Returns the square root of a number |
tan(x) | Returns the tangent of an angle |
valueOf() | Returns the primitive value of a Math object |
Properties | |
E | Returns Euler's constant (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.414) |
LOG10E | Returns the base-10 logarithm of E (approx. 0.434) |
PI | Returns PI (approx. 3.14159) |
SQRT1_2 | Returns the square root of 1/2 (approx. 0.707) |
SQRT2 | Returns the square root of 2 (approx. 1.414) |
Put goodie sample here
window. Property |
Description |
---|---|
closed | Returns whether or not a window has been closed |
document | See Document object |
history | See History object |
length | Sets or returns the number of frames in the window |
location | See Location object |
name | Sets or returns the name of the window |
opener | Returns a reference to the window that created the window |
parent | Returns the parent window |
self | Returns a reference to the current window |
top | Returns the topmost ancestor window |
window. Methods |
Description |
alert() | Displays an alert box with a message and an OK button |
blur() | Removes focus from the current window |
clearInterval() | Cancels a timeout set with setInterval() |
clearTimeout() | Cancels a timeout set with setTimeout() |
close() | Closes the current window |
confirm() | Displays a dialog box with a message and an OK and a Cancel button |
focus() | Sets focus to the current window |
moveBy() | Moves a window relative to its current position |
moveTo() | Moves a window to the specified position |
open() | Opens a new browser window |
print() | Prints the contents of the current window |
prompt() | Displays a dialog box that prompts the user for input |
resizeBy() | Resizes a window by the specified pixels |
resizeTo() | Resizes a window to the specified width and height |
scrollBy() | Scrolls the content by the specified number of pixels |
scrollTo() | Scrolls the content to the specified coordinates |
setInterval() | Evaluates an expression at specified intervals |
setTimeout() | Evaluates an expression after a specified number of milliseconds |
location. Property |
Description |
hash | Sets or returns the URL from the hash sign (#) |
host | Sets or returns the hostname and port number of the current URL |
hostname | Sets or returns the hostname of the current URL |
href | Sets or returns the entire URL |
pathname | Sets or returns the path of the current URL |
port | Sets or returns the port number of the current URL |
protocol | Sets or returns the protocol of the current URL |
search | Sets or returns the URL from the question mark (?) |
location. Method |
Description |
assign() | Loads a new document |
reload() | Reloads the current document |
replace() | Replaces the current document with a new one |
document. Collection |
Description |
---|---|
anchors[] | Returns a reference to all Anchor objects in the document |
forms[] | Returns a reference to all Form objects in the document |
images[] | Returns a reference to all Image objects in the document |
links[] | Returns a reference to all Area and Link objects in the document |
document. Property |
Description |
body | Gives direct access to the <body> element |
cookie | Sets or returns all cookies associated with the current document |
domain | Returns the domain name for the current document |
lastModified | Returns the date and time a document was last modified |
referrer | Returns the URL of the document that loaded the current document |
title | Returns the title of the current document |
URL | Returns the URL of the current document |
document. Method |
Description |
close() | Closes an output stream opened with the document.open() method, and displays the collected data |
getElementById() | Returns a reference to the first object with the specified id |
getElementsByName() | Returns a collection of objects with the specified name |
getElementsByTagName() | Returns a collection of objects with the specified tagname |
open() | Opens a stream to collect the output from any document.write() or document.writeln() methods |
write() | Writes HTML expressions or JavaScript code to a document |
writeln() | Identical to the write() method, with the addition of writing a new line character after each expression |
Property | Tags applicable | Description | |||
---|---|---|---|---|---|
abbr | <td> | Sets or returns an abbreviated version of the content in a table cell | |||
accessKey | <a> | <area> | <button> | Sets or returns a keyboard key to access a link | |
align | <img> | <object> | <iframe> | <td>,<tr> | Sets or returns how to align an image according to the surrounding text |
alt | <img> | <area> | Sets or returns an alternate text to be displayed, if a browser cannot show an area | ||
archive | <object> | Sets or returns a string that can be used to implement your own archive functionality for the object | |||
axis | <td> | Sets or returns a comma-delimited list of related table cells | |||
border | <img> | <table> | Sets or returns the border around an image | ||
caption | <table> | Sets or returns the caption of a table | |||
cellIndex | <td> | Returns the position of a cell in the cells collection of a row | |||
cellPadding | <table> | Sets or returns the amount of space between the cell border and cell content | |||
cellSpacing | <table> | Sets or returns the amount of space between the cells in a table | |||
charset | <a> | <link> | Sets or returns the character-set of the linked resource | ||
code | <object> | Sets or returns the URL of the file that contains the compiled Java class | |||
codeBase | <object> | Sets or returns the URL of the component | |||
cols | <frameset> | Sets or returns the number of columns in a frameset | |||
colSpan | <td> | Sets or returns the number of columns a table cell should span | |||
complete | <img> | Returns whether or not the browser has finished loading the image | |||
content | <meta> | Sets or returns the value of the content attribute of a <meta> element | |||
coords | <a> | <area> | Sets or returns a comma-separated list with coordinates of a link in an image-map | ||
disabled | <button> | <link> | Sets or returns whether a button should be disabled | ||
form | <button> | Returns a reference to the form that contains the button | |||
frame | <table> | Sets or returns the outer-borders of a table | |||
frameBorder | <frame> | Sets or returns whether or not to display borders around a frame | |||
hash | <area> | Sets or returns the anchor part of the URL in an area | |||
height | <img> | <iframe> | Sets or returns the height of an image | ||
host | <area> | Sets or returns the hostname and port of the URL in an area | |||
href | <a> | <area> | <base> | <link> | Sets or returns the URL of the linked resource |
hreflang | <a> | <link> | Sets or returns the language code of the linked resource | ||
hspace | <img> | <object> | Sets or returns the white space on the left and right side of the image | ||
httpEquiv | <meta> | Connects the content attribute to an HTTP header | |||
id | <a>,<base>,<area>,<body>,<button>,<tr> | <object>,<frame>,<iframe>,<img>, <link>,<frameset>,<table>,<td> | |||
innerHTML | <a> | <td> | <tr> | Sets or returns the text of a link | |
isMap | <img> | Returns whether or not an image is a server-side image map | |||
longDesc | <img> | <frame> | <iframe> | Sets or returns a URL to a document containing a description of the image | |
lowsrc | <img> | Sets or returns a URL to a low-resolution version of an image | |||
marginHeight | <frame> | <iframe> | Sets or returns the top and bottom margins of a frame | ||
marginWidth | <frame> | <iframe> | Sets or returns the left and right margins of a frame | ||
media | <link> | Sets or returns on what device the document will be displayed | |||
name | <a>,<meta>,<img>,<button>,<link>,<frame> | <object>,<iframe> | |||
noHref | <area> | Sets or returns whether an area should be active or inactive | |||
noResize | <frame> | Sets or returns whether or not a frame can be resized | |||
pathname | <area> | Sets or returns the pathname of the URL in an area | |||
protocol | <area> | Sets or returns the protocol of the URL in an area | |||
rel | <a> | <link> | Sets or returns the relationship between the current document and the target URL | ||
rev | <a> | <link> | Sets or returns the relationship between the target URL and the current document | ||
rowIndex | <tr> | Returns the position of a row in the table's rows collection | |||
rows | <frameset> | Sets or returns the number of rows in a frameset | |||
rowSpan | <td> | Sets or returns the number of rows a table cell should span | |||
rules | <table> | Sets or returns the inner-borders of a table | |||
scheme | <meta> | Sets or returns the format to be used to interpret the value of the content attribute | |||
search | <area> | Sets or returns the query string part of the URL in an area | |||
shape | <a> | <area> | Sets or returns the shape of a link in an image-map | ||
src | <img> | <frame> | <iframe> | Sets or returns the URL of an image | |
summary | <table> | Sets or returns a description of a table | |||
tabIndex | <a> | <area> | <button> | <object> | Sets or returns the tab order for a link |
target | <a> | <area> | <base> | Sets or returns where to open a link | |
tFoot | <table> | Returns the TFoot object of a table | |||
tHead | <table> | Returns the THead object of a table | |||
type | <a> | <button> | <link> | Sets or returns the MIME type of the linked resource | |
useMap | <img> | Sets or returns the value of the usemap attribute of an client-side image map | |||
vAlign | <td> | <tr> | Sets or returns the vertical alignment of data within a table cell | ||
value | <button> | Sets or returns the text that is displayed on a button | |||
vspace | <img> | <object> | Sets or returns the white space on the top and bottom of the image | ||
width | <img> | <table> | <iframe> | <td> | Sets or returns the width of an image |
Property | Standard Properties | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
className | <a> | <frame> | <td> | <area> | <frameset> | <button> | <iframe> | <img> | <table> | <body> | <object> | Sets or returns the class attribute of an element |
dir | <a> | <frame> | <td> | <area> | <frameset> | <button> | <iframe> | <link> | <table> | <body> | <object> | Sets or returns the direction of text |
lang | <a> | <frame> | <td> | <area> | <frameset> | <button> | <iframe> | <link> | <table> | <body> | <object> | Sets or returns the language code for an element |
title | <a> | <frame> | <td> | <area> | <frameset> | <button> | <iframe> | <img> | <table> | <body> | <object> | Sets or returns an element's advisory title |
Method | tag | Description |
---|---|---|
blur() | <a> | Removes focus from the link |
focus() | <a> | Gives focus to the link |
rows[] | <table> | Returns an array containing each row in a table |
tBodies[] | <table> | Returns an array containing each tbody in a table |
createCaption() | <table> | Creates a caption element for a table |
createTFoot() | <table> | Creates an empty tFoot element in a table |
createTHead() | <table> | Creates an empty tHead element in a table |
deleteCaption() | <table> | Deletes the caption element and its content from a table |
deleteRow() | <table> | Deletes a row from a table |
deleteTFoot() | <table> | Deletes the tFoot element and its content from a table |
deleteTHead() | <table> | Deletes the tHead element and its content from a table |
insertRow() | <table> | Inserts a new row in a table |
deleteCell() | <tr> | Deletes a cell in a table row |
insertCell() | <tr> | Inserts a cell in a table row |
cells[] | <tr> | Returns an array containing each cell in the table row |