Javascript
Basics
- When possible make references, don't hard code.
- When updating look via javascript set or update element classes, do not set style directly.
Some Helpful Information
-
Data and structure types
Type Description Example Boolean A binary variable of two possible values - 'true' or 'false'. variable = true; Null Represents the intentional absence of any value. variable = null; Undefined A variable that has not been assigned a value. variable; Number Numbers can be written with or without decimals. variable = 7; String Strings are values wrapped in quotes. variable = "text"; Array Useful for storing multiple values in a single variable.
Organized as key value pairs.
Key is the number order of values starting with 0.
In the example: variable[0] = "alpha" and variable[1] = "beta" ...
MDN Array pagevariable = [ "alpha", "beta", "charlie" ];
Object Useful for storing multiple values in a single variable.
Organized as name value pairs.
In the example: variable.hair = "red" ...
MDN Object pagevariable = { hair: "red", eyes: "blue", age: 45 };
-
Is variable set?
if (typeof variable === "undefined") { /*variable has not been set*/ } if (typeof variable !== "undefined") { /*variable has been set*/ }
-
Sort an array
const example = [ { name: "oranges", count: 9 }, { name: "bananas", count: 6 }, { name: "apples", count: 14 } ]; const sortByName = (a, b) => { const x = a.name; const y = b.name; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; const sortByCount = (a, b) => { const x = a.count; const y = b.count; return x - y; }; How to use: example.sort(sortByName); or example.sort(sortByCount);
-
Harvest URL variables
URL searchParams - Note: does not work in IE
Specific URL variable
example url = http://website.com/?who=me&what=testing&where=here const who = (new URL(document.location)).searchParams.get('who') // me
All URL variables
example url = http://website.com/?who=me&what=testing&where=here const urlVars = []; (new URL(document.location)).searchParams.forEach((value, key) => { urlVars[key] = value; }); urlVars now equals { what: "testing" where: "here" who: "me" }
-
Random Numbers
Math.floor(Math.random()*max number);
Create random number from 0 to value before max. Math.random creates a random number between 0 and 1. Multiple that by your max number and use Math.floor to cut off the number at the decimal point. Do not use Math.round, the first and last numbers will get less hits.
-
Verify user wants to leave the webpage
window.onbeforeunload = function() { return "Leave this webpage?"; }