Javascript
Javascript
Subpage Table of Contents
Load Script
External Script
<script type="text/javascript" src="myscript.js"></script>
Inline: (in html head or body)
<script type="text/JavaScript"> <!-- // some javascript... // --> </script>
References
DevGuru JavaScript Quick Reference Methods Index
Page Refresh
Example: [1]
<a href="javascript:location.reload(true)">Refresh this page</a>
Other triggers:
<input type="button" value="Reload Page" onClick="window.location.reload()"> <input type="button" value="Reload Page" onClick="history.go(0)"> <input type="button" value="Reload Page" onClick="window.location.href=window.location.href">
Auto Page Refresh
Example: [2]
<!-- Codes by Quackit.com --> <html> <head> <script type="text/JavaScript"> <!-- function timedRefresh(timeoutPeriod) { setTimeout("location.reload(true);",timeoutPeriod); } // --> </script> </head> <body onload="JavaScript:timedRefresh(5000);"> <p>This page will refresh every 5 seconds. This is because we're using the 'onload' event to call our function. We are passing in the value '5000', which equals 5 seconds.</p> <p>But hey, try not to annoy your users too much with unnecessary page refreshes every few seconds!</p> </body> </html>
Refresh using META-Refresh
Change span content
Change span content [3]
document.getElementById("someelement").innerHTML="...";
// <span id="posting:oTxtIgnoreAdd" onclick="ChangeText(this)'">Add</span> ... function ChangeText(field){ field.innerHTML='Ignore'; }
auto refresh image
<script type="text/javascript" src="camera.js"></script> <body onload="updateImage();"> ... var newImage = new Image(); newImage.src = "http://localhost/image.jpg"; function updateImage() { if(newImage.complete) { document.getElementById("theText").src = newImage.src; newImage = new Image(); number++; newImage.src = "http://localhost/image/id/image.jpg?time=" + new Date(); } setTimeout(updateImage, 1000); }
Maybe:
newImage.src = "..." + new Date().getTime();
References:
- javascript - Refresh image with a new one at the same url - Stack Overflow - http://stackoverflow.com/questions/1077041/refresh-image-with-a-new-one-at-the-same-url
onclick
<a href="" onhover="dosomething();" onmouseover="dosomethingelse();" onclick="return false;">Do Something</a>
AJAX
function get_active() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { document.getElementById("status").innerHTML = "Loading..."; if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("activesprinkler").value = xmlhttp.responseText; } } xmlhttp.open("GET", "sprinkler.py", true); xmlhttp.send(); }
WARNING: don't try opening a file on another server, it won't work, due to security constraints!
AJAX Send an XMLHttpRequest To a Server - http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
AJAX Tutorial - http://www.w3schools.com/ajax/
Detect IE Version
if(navigator.appName.indexOf("Internet Explorer")!=-1){ //yeah, he's using IE var badBrowser=( navigator.appVersion.indexOf("MSIE 9")==-1 && //v9 is ok navigator.appVersion.indexOf("MSIE 1")==-1 //v10, 11, 12, etc. is fine too ); if(badBrowser){ // navigate to error page alert('WARNING: PAGE WILL LOOK BROKEN!\nYou really should upgrade to IE 10, or even better switch to Firefox/Chrome!'); } }
Modified from source: http://stackoverflow.com/questions/10964966/detect-ie-version-in-javascript
--
function isIE () { var myNav = navigator.userAgent.toLowerCase(); return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false; } if (isIE () < 10) { ... }
Javascript from Command Line
Use the '/usr/bin/js' command.
js - JavaScript interpreter - http://www.mozilla.org/js/
- "JavaScript is the Netscape-developed object scripting language used in millions of web pages and server applications worldwide. Netscape's JavaScript is a superset of the ECMA-262 Edition 3 (ECMAScript) standard scripting language, with only mild differences from the published standard."
Based on SpiderMonkey - Information specific to JavaScript in C engine (aka SpiderMonkey) embedding.
WARNING: "Note: Because the JavaScript shell is used as a test environment for the JavaScript engine, the available options and built-in functions can change over time." [4]
WARNING: DOES NOT INCLUDE MANY COMMON JAVASCRIPT OBJECTS AND FUNCTIONS:
- alert()
- console.log()
- Object.getOwnPropertyNames(obj)
Documentation:
- Introduction to the JavaScript shell - Mozilla | MDN - https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell
Installation:
# epel or rpmforge yum install js
Code:
js> print('hi') hi js> 6*7 42 js> function f() { return a; } js> var a = 34; js> f() 34 js> Math.random() 0.7849307000430139 js> typeof Math object js> var o = new Object(); js> quit()
Script:
$ js echo.js test1 test2 test1 test2 $ cat echo.js for (i in arguments) { print(arguments[i]) }
Other commands:
js> help() JavaScript-C 1.7.0 2007-10-03 Command Usage Description ======= ===== =========== version version([number]) Get or set JavaScript version number options options([option ...]) Get or toggle JavaScript options load load(['foo.js' ...]) Load files named by string arguments readline readline() Read a single line from stdin print print([exp ...]) Evaluate and print expressions help help([name ...]) Display usage and help messages quit quit() Quit the shell gc gc() Run the garbage collector trap trap([fun, [pc,]] exp) Trap bytecode execution untrap untrap(fun[, pc]) Remove a trap line2pc line2pc([fun,] line) Map line number to PC pc2line pc2line(fun[, pc]) Map PC to line number stringsAreUtf8 stringsAreUTF8() Check if strings are UTF-8 encoded testUtf8 testUTF8(mode) Perform UTF-8 tests (modes are 1 to 4) throwError throwError() Throw an error from JS_ReportError build build() Show build date and time clear clear([obj]) Clear properties of object intern intern(str) Internalize str in the atom table clone clone(fun[, scope]) Clone function object seal seal(obj[, deep]) Seal object, or object graph if deep getpda getpda(obj) Get the property descriptors for obj getslx getslx(obj) Get script line extent toint32 toint32(n) Testing hook for JS_ValueToInt32 evalcx evalcx(s[, o]) Evaluate s in optional sandbox object o if (s == '' && !o) return new o with eager standard classes if (s == 'lazy' && !o) return new o with lazy standard classes
Note: Seems pretty useless, or just a toy. Couldn't figure out how to read/write files, execute programs or do other system level operations (although some version do).
References:
- unix - Executing Javascript without a browser? - Stack Overflow - http://stackoverflow.com/questions/2941411/executing-javascript-without-a-browser
- Rhino shell - Mozilla | MDN - https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Shell
jQuery
See jQuery
Chrome JavaScript Console
You can enter JavaScript manually into Chrome's JavaScript Console. It also has code completion functionality, which is really useful!
CTRL + SHIFT + J
Best if you start with a blank page:
about:blank
Enter multi line with
SHIFT + ENTER
Execute code with
ENTER
var testf = function(count) { for (var i = 0 ; i < count; i++) { console.log(i + " x"); } }; testf(10);
code
comments
c style comments
// in line comment /* multi line comment */
variables
var myvar; var mystr = "hello world\n"; var myint = 1; var myarray = []; var mydict = {}; var mybool = false;
alert
Post message alert to browser
alert("some message");
prompt
Prompt for a response:
var name = prompt("name"); // null if cancel or x
confirm
var answer = confirm("yes or no?"); // true, false if cancel or x
console
Post message to browser's development console log
console.log("some message");
math
1 + 1; // + - * / % 3 / 2; // 1.5 3 % 2; // 1 2 + (3 * 2); // 8
a > b; // > >= < <=
++i; i++; // return value before or after decrement --i; i++; // only makes a difference with inline math (5 + ++i), which you should avoid anyway
x += 1; x -= 1; x *= 1; x /= 1;
var div = Math.floor(y/x); var rem = y % x;
fake integer division: [5]
var num = ~~(a / b); var num = (a / b) >> 0;
Random:
Math.random(); // 0.898123... Math.floor(Math.random() * 4); // 0, 1, 2, 3
comparision
a == b; // equal-ish (eg. "5" == 5 or 0 == false) a === b; // exactly equal (eg. 5 === 5) a !== b; // not exactly equal (eg. 5 !== 4)
boolean
true && false; // false true || false; // true ! true; // false
strings
"hello"; 'hello'; "hello" + "world"; "hello world".slice(2, 4); // "ll" (start, end+1) "hello".length; // 5 "hello"[0]; // "h" "hello".toUpperCase(); "hello".toLowerCase();
const fruit = ['apple', 'bananna']; if(fruit.includes('apple', 0)) { ... }
null and undefined
var myVariable; // myVariable is undefniend (eg. myVariable === undefined) var myVariable = null; // myVariable is null - used to deliberately say it is empty (eg. myVariable === null)
if
if (condition) { ... } else if (condition) { ... } else { ... }
loops
while (condition) { ... }
// for (setup; condition; increment) { ... } for (var i = 0; i < max; i++) { ... }
for (var key in obj) { ... }
break; continue;
function
// function declaration version function myfunc(var1, var2) { return false; }
// function expression version var myfunc = function(var) { ... };
// call function var value = myfunc(var);
--- unlimited arguments ---
function manyArgs() { var args = []; for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i]; // ... } function foo() { var args = Array.prototype.slice.call(arguments, 0); // ... }
Source: http://stackoverflow.com/questions/6396046/unlimited-arguments-in-a-javascript-function
array
var myarray = []; // empty array
var myarray = ["1", 2, 3.141]; myarray[0]; // "1" myarray.length; // 3 myarray.indexOf("1"); // 0 myarray[myarray.length - 1]; // returns last item (eg 3.141)
myarray.unshift("first"); // returns new size of array and puts item at front myarray.push("last"); // returns new size of array and puts item on end myarray.pop(); // returns last item and removes it myarray.shift(); // returns first item and removes it // Stacks: Last In, First Out (LIFO) // Queues: First In, First Out (FIFO)
firstArray.concat(secondArray); // join 2 arrays firstArray.concat(secondArray, thirdArray, ...); // join multiple arrays
var multiarray = ["1", ["name", "date"], 2]; multiarray[1][0]; // "name"
var mystr = myarray.join(); // join array to string separated by commas (no spaces) var mystr = myarray.join(", "); // join array to string separated by commas and spaces
var keys = [] for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } keys.sort();
random
function getRandomNumber(minimum, maximum) { rno = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; return rno }
json
JSON is native JavaScript Object Notation!
var testdata = [ { "apple": { "size": 1163, "color": "red" } }, { "pumpkin": { "size": 916, "color": "orange" } }, ];
Objects
var myemptyobj = {};
// build object with "object literal" var myobj = {"name": "test", "color": "blue"}; // created with an "object literal" - coding whole value all at once var myobj = {color: "blue", "full name": "mr smith"}; // keys are always strings, so quotes only needed with spaces
// access object items myobj["name"]; var val = myobj[key]; myobj.name; // dot notation, only works if key doesn't have spaces Object.keys(myobj); // array of keys
// build object afterwards var myobj = {}; myobj["name"] = "mr smith"; // building object afterwards myobj.color = "blue"; // dot notaiton, only works if key doesn' thave spaces
// array of objects myarray = [ { name: "test" }, ... ]; myarray[0]["name"]; myarray[0].name;
// functions can be attached, and this object can be referenced with 'this' myobj.myfunc = function() { ...; this.some_property; }
Classes
There are no classes in JavaScript (no inheritance). Just functions/objects with sub functions/objects/properties.
Advanced Code
Objects Advanced
Constructor - function that creates objects and gives them a set of built-in properties and methods
var MyObj = function(x, y) { this.x = x; this.y = y; }; var obj = new MyObj(var1, var2);
Prototypes - defines methods for constructor
var MyObj = function(x, y) { this.x = x; this.y = y; }; MyObj.prototype.draw = function () { ... } var obj = new MyObj(1, 2); obj.draw();
Introspection and Reflection
reflection provides a mechanism to self-inspect and manipulate its member attributes and methods
typeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name:'John', age:34} // Returns object
Object.getOwnPropertyNames(obj); // Returns all property names
for (var key in obj) { console.log(key); }
Getting an Object's Public Attributes:
var getProperties = function(obj) { var properties = []; for (var prop in obj) { if (typeof obj[prop] != 'function') { properties.push(prop); } } return properties; };
Getting All the Public Methods of a Class
var getMethods = function(obj) { var methods = []; for (var method in obj) { if (typeof obj[method] == 'function') { methods.push(method); } } return methods; };
References:
- Object Reflection in JavaScript - http://www.htmlgoodies.com/tutorials/web_graphics/object-reflection-in-javascript.html
DOM
Document Object Model (DOM) - access content of a web page
<h1 id="main">Hello</h1>
var mainElement = document.getElementById("main"); mainElement.innerHTML; mainElement.innerHTML = newHTML;
Document:
document.write(someHTML);
Timeout
var timeout_id = setTimeout(func, timeout); // timeout in milliseconds
clearTimeout(timeout_id);
// Repeating timeout var timeout_id = setInterval(func, interval); // interval in milliseconds
jQuery
See jQuery
Canvas
drawing on the canvas
<canvas id="canvas" width="200" height="200"></canvas>
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d");
// draw text ctx.font = "20px Courier"; ctx.fillStyle = "Black"; ctx.textAlign = "left"; // left, center, right ctx.textBaseline = "top"; // bottom, middle, top ctx.fillText("hello world", 50, 50);
// draw solid square ctx.fillStyle = "Red"; ctx.fillRect(0, 0, 10, 10);
// draw rectangle ctx.strokeStyle = "DeepPink"; ctx.lineWidth = 4; ctx.strokeRect(10, 10, 100, 20);
// draw lines ctx.strokeStyle = "Turquoise"; ctx.lineWidth = 4; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(60, 60); ctx.moveTo(60, 10); ctx.lineTo(10, 60); ctx.stroke();
// draw fill path ctx.fillStyle = "SkyBlue"; ctx.beginPath(); ctx.moveTo(100, 100); ctx.lineTo(100, 60); ctx.lineTo(130, 30); ctx.lineTo(160, 60); ctx.lineTo(160, 100); ctx.lineTo(100, 100); ctx.fill();
// draw circle // 0 radians = 0 degrees // pi / 2 radians = 90 degrees // pi radians = 180 degrees // pi * 3/2 radians = 270 degrees // pi * 2 radians = 360 degrees ctx.lineWidth = 2; ctx.strokeStyle = "Green"; ctx.beginPath(); ctx.arc(50, 50, 20, 0, Math.PI / 2, false); ctx.stroke();
// draw circle function var circle = function (x, y, radius) { ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2, false); ctx.stroke(); };
Colors: http://css-tricks.com/snippets/css/named-colors-and-hex-equivalents/
--- Sample Bee ---
<canvas id="canvas" width="200" height="200"></canvas> <script> var circle = function (x, y, radius, fillCircle) { ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2, false); if (fillCircle) { ctx.fill(); } else { ctx.stroke(); } }; var drawBee = function (x, y) { ctx.lineWidth = 2; ctx.strokeStyle = "Black"; ctx.fillStyle = "Gold"; circle(x, y, 8, true); circle(x, y, 8, false); circle(x - 5, y - 11, 5, false); circle(x + 5, y - 11, 5, false); circle(x - 2, y - 1, 2, false); circle(x + 2, y - 1, 2, false); }; var update = function (coordinate) { var offset = Math.random() * 4 - 2; coordinate += offset; if (coordinate > 200) { coordinate = 200; } if (coordinate < 0) { coordinate = 0; } return coordinate; }; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var x = 100; var y = 100; setInterval(function () { ctx.clearRect(0, 0, 200, 200); drawBee(x, y); x = update(x); y = update(y); ctx.strokeRect(0, 0, 200, 200); }, 30); </script>
Epoch Timestamp
if (!Date.now) { Date.now = function() { return new Date().getTime(); } }
References:
- datetime - How do you get a timestamp in JavaScript? - Stack Overflow - http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript
Examples
Dim Image
this.style.opacity=0.6
function dimImage(tagid) { var img = document.getElementById(tagid); img.style.opacity = 0.6; } function undimImage(tagid) { var img = document.getElementById(tagid); img.style.opacity = 1; }
References:
- javascript - How to darken an image on mouseover? - Stack Overflow - http://stackoverflow.com/questions/1747637/how-to-darken-an-image-on-mouseover