Javascript
-
Variables
-
Type Description Example Boolean Boolean represents a logical entity and can have two values: true, and false. var variable = true; Null The value null represents the intentional absence of any object value. var variable = null; Undefined A variable that has not been assigned a value has the value undefined. var variable; Number Numbers can be written with, or without decimals. var variable = 7; String Strings are written with quotes. You can use single or double quotes. var 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" ... var variable = [ "alpha", "beta", "charlie" ]; Object Useful for storing multiple values in a single variable. Like an Array, but written as name:value pairs (name and value separated by a colon).In the example: variable.hair = "red" ... var variable = { hair: "red", eyes: "blue", age: 45 }; -
if (typeof variable === "undefined") { /*variable has not been set*/ } if (typeof variable !== "undefined") { /*variable has been set*/ }
-
var sortByName = function (a, b) { var x = a.name; var y = b.name; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } var sortByDistance = function (a, b) { var x = a.distance; var y = b.distance; return x - y; }
How to use:
tracks.sort(sortByName);
or
tracks.sort(sortByDistance);
Example array:
var tracks = [ {distance: 9, name: "nine"}, {distance: 6, name: "six"}, {distance: 14, name: "fourteen"} ];
-
Here is an easy to use function to get variables from the URL.
var getURLvar = function (i) { var h = location.href; var q = h.indexOf("?" + i + "="); var a = h.indexOf("&" + i + "="); if (q > -1 || a > -1) { var x = (q > a) ? q : a; var s = x + (i.length + 2); if (h.indexOf("&", s) > -1) { var e = h.indexOf("&", s); } else if (h.indexOf("#", s) > -1) { var e = h.indexOf("#", s); } else { var e = h.length; } return h.substring(s,e); } else { return ""; } };
How to use:
var variable = getURLvar("url variable");
-
Here is a function that will get all the variables from the URL.
var harvestURLvariables = function () { var urlVars = []; if (location.href.indexOf("?") > -1) { var i = location.href.substring(location.href.indexOf("?")+1); while (i.indexOf("=") > -1) { var key = i.substring(0,i.indexOf("=")); var s = i.indexOf("=") + 1; var e = 0; if (i.indexOf("&", s) > -1) { e = i.indexOf("&"); } else if (i.indexOf("#", s) > -1) { e = i.indexOf("#"); } else { e = i.length; } var val = i.substring(s,e); var urlVar = {[key]: val}; urlVars.push(urlVar); i = i.substring(e + 1); } } return urlVars; }
How to use:
var urlVars = harvestURLvariables();
-
-
Useful Stuff
-
Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
(function () { /* ... */ })();
-
A closure is the combination of a function and the lexical environment within which that function was declared. Mozilla MDN Web Docs Closure Page
HTML
<div> <button type="button">0</button> <button type="button">1</button> <button type="button">2</button> </div>
Javascript
(function () { "use strict"; var buttons = document.getElementsByTagName("button"); for (var n = 0; n < buttons.length; n++) { buttons[n].addEventListener("click", buttonClick(n)); } var buttonClick = function (n) { return function() { console.log(n); }; } })();
Adding return function inside the function that is called causes a new function to be created for each click call solving the for loop increment issue.
-
var cookie = { get: function (i) { if (document.cookie.length > 0) { var s = document.cookie.indexOf(i + "="); if (s !== -1) { s = s + (i.length + 1); var e = document.cookie.indexOf(";", s); if (e === -1) { e = document.cookie.length; } return document.cookie.substring(s, e); } else { return ""; } } else { return ""; } }, set: function (i, v) { var exdate = new Date(); exdate.setDate(exdate.getDate() + 999); document.cookie = i + "=" + v + ";expires=" + exdate.toGMTString(); } };
How to get:
var variable = cookie.get(cookie variable);
How to set:
cookie.set(cookie variable, cookie value);
-
Here is an easy to use function to get data via AJAX (get or post)
var AjaxData = function (i, i2) { var r = null; try { r = new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari catch (e) { try { r = new ActiveXObject("Msxml2.XMLHTTP"); } // Internet Explorer catch (e) { r = new ActiveXObject("Microsoft.XMLHTTP"); } } if (r === null) { alert ("Your browser does not support AJAX!"); return; } i = (i.indexOf("#") > -1) ? i = i.substring(0, i.indexOf("#")); if (i.indexOf("?") > -1) { // add nocache var i += "&nocache=" + new Date().getTime(); } else { i += "?nocache=" + new Date().getTime(); } if (i2 === undefined) { r.open("GET",i,true); r.send(null); } else { r.open("POST",i,true); r.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); r.send(i2); } return r; }
Example (post):
var u = "information_i_want.html"; var v = "postvar1=abc&postvar2=def"; var r = ajaxData(u, v); r.onreadystatechange = function () { if (r.readyState === 4 || r.readyState === "complete") { //the response info is r.responseText //this is where you put stuff you want to happen based on the response } }
-
var parseXML = function (xml) { var getSubtagName = function (i) { if (i.indexOf("=") > -1) { var e = i.indexOf("="); var s = i.lastIndexOf(" ", e) + 1; return i.substring(s, e); } else { return ""; } }; var getSubtags = function (i) { var o = []; while (getSubtagName(i) !== "") { var subtagName = getSubtagName(i); var subtagValue = getSubtagValue(i, subtagName); var e = i.indexOf(subtagValue); i = i.substring(e); o[subtagName] = subtagValue; } return o; }; var getSubtagValue = function (i, subtagName) { var s = i.indexOf(subtagName + "=") + 2 + subtagName.length; var c = i.substr(s - 1, 1); if (c !== '"' && c !== "'" && c !== "\\") { throw "Malformed XML data. Missing ' or \" after = for subtag " + subtagName + "."; } if (c === "\\") { c = i.substr(s - 1, 2); s++; } var match = false; var e = s; while (!match && i.indexOf(c, e) > -1) { e = i.indexOf(c, e); if (c.length === 2 || i.substr(e - 1, 1) !== "\\") { match = true; } else { e++; } } if (match) { return i.substring(s, e); } else { throw "Malformed XML data. No closing ' or \" to subtag " + subtagName + "."; } }; var getTag = function (i) { if (i.indexOf("<") > -1 && i.indexOf(">") > -1) { var s = i.indexOf("<") + 1; var e = i.indexOf(">"); return i.substring(s, e); } else { return ""; } }; var getTagName = function (i) { if (i.indexOf(" ") > -1) { var e = i.indexOf(" "); return i.substr(0, e); } else { return i; } }; var getTags = function (i, o) { var e = ""; if (o === undefined) { o = []; } while (getTag(i) !== "") { var subtags = ""; var tag = getTag(i); var tagName = getTagName(tag); var tagType = getTagType(tag, tagName); if (tagType === "comment") { e = i.indexOf("-->") + 3; i = i.substring(e); } else if (tagType === "xml tag" || tagType === "self closing tag") { subtags = getSubtags(tag); if (tagType === "self closing tag") { if (typeof o[tagName] === "undefined") { o[tagName] = [subtags]; } else { o[tagName].push(subtags); } } else { o[tagName] = subtags; } e = i.indexOf(tag) + tag.length + 1; i = i.substring(e); } else if (tagType === "opening tag") { var tagValue = getTagValue(i, tagName); subtags = ""; if (tag.indexOf("=") > -1) { subtags = getSubtags(tag); } else { subtags = ""; } i = removeTag(i, tagName); if (tagValue.substr(0, 9) === "<![CDATA[" || getTag(tagValue) === "") { if (tagValue.substr(0, 9) === "<![CDATA[") { var s = 9; e = tagValue.indexOf("]]>") - 9; tagValue = tagValue.substr(s, e); } if (subtags !== "") { if (typeof o[tagName] === "undefined") { o[tagName] = [subtags]; o[tagName][0].push(tagValue); } else { var len = o[tagName].length; o[tagName][len] = subtags; o[tagName][len].push(tagValue); } } else { if (typeof o[tagName] === "undefined") { o[tagName] = [tagValue]; } else { o[tagName].push(tagValue); } } } else { if (subtags !== "") { if (typeof o[tagName] === "undefined") { o[tagName] = [getTags(tagValue, subtags)]; } else { o[tagName].push(getTags(tagValue, subtags)); } } else { if (typeof o[tagName] === "undefined") { o[tagName] = [getTags(tagValue)]; } else { o[tagName].push(getTags(tagValue)); } } } } } return o; }; var getTagType = function (i, tagName) { if (i.substr(0, 3) === "!--") { return "comment"; } else if (tagName === "?xml") { return "xml tag"; } else if (i.substr(0, 1) === "/") { throw "Malformed XML data. When looking for new tag, found closing tag " + tagName + "."; } else if (i.substring(i.length - 1) === "/") { return "self closing tag"; } else { return "opening tag"; } }; var getTagValue = function (i, tagName) { var s = i.indexOf(">") + 1; if (i.indexOf("" + tagName + ">", s) > -1) { var e = i.indexOf("" + tagName + ">", s); return i.substring(s, e); } else { throw "Malformed XML data. No closing tag for " + tagName + "."; } }; var removeTag = function (i, tagName) { if (i.indexOf("" + tagName + ">") > -1) { var e = i.indexOf("" + tagName + ">") + tagName.length + 3; return i.substring(e); } else { throw "Malformed XML data. No closing tag for " + tagName + "."; } }; try { return getTags(xml); } catch (err) { console.log(err); } };
How to call:
var output = parseXML(xml);
If you need to put HTML code in your XML file, don't forget to protect the html data in <![CDATA[html code ]]>
Example XML
<?xml version="1.0" encoding="ISO-8859-1" ?> <guestbook type="friend's"> <guest type="blank" /> <guest type="friend"> <fname type="strange">Terje</fname> <lname>Beck</lname> </guest> <!-- <guest> <fname>Frank</fname> <lname>Babbis</lname> </guest> --> <guest> <fname>Jan</fname> <lname>Refsnes</lname> </guest> </guestbook>
Multidimensional array output
[?xml] [version] => 1.0 [encoding] => ISO-8859-1 [guestbook] [0] [type] => friend [guest] [0] [type] => blank [1] [type] => friend [fname] [type] => strange [0] => Terje [lname] [0] => Beck [2] [fname] [0] => Jan [lname] [0] => Refsnes
-
You have a form input field for date information. Instead of having the user type in the date (hopefully correctly), you would like to have a month calendar box for the user to pick a date from. Here is the solution.
Javascript
(function () { "use strict"; var pickAdate = function(evt) { var settings = { date: { day: 0, month: 0, year: 0, startMonth: 0, startYear: 0 }, datebox: "", dateboxCover: "", datefield: "", }; var view = { init: function(i) { view.position(i); }, position: function (i) { settings.datefield = i; if (settings.datebox === "") { settings.datebox = document.createElement("div"); settings.datebox.className = "pickAdate"; document.body.appendChild(settings.datebox); } else { settings.datebox.style.display = "block"; } var findLeft = function (i) { var left = i.offsetLeft; while (i.offsetParent) { i = i.offsetParent; left += i.offsetLeft; } return left; }; var findTop = function (i) { var top = i.offsetTop; while (i.offsetParent) { i = i.offsetParent; top += i.offsetTop; } return top; }; settings.datebox.style.left = findLeft(i) + "px"; settings.datebox.style.top = findTop(i) + "px"; settings.datebox.addEventListener("click", controller.dateboxClick); if (settings.dateboxCover === "") { settings.dateboxCover = document.createElement("div"); settings.dateboxCover.className = "pickAdateCover"; document.body.appendChild(settings.dateboxCover); settings.dateboxCover.addEventListener("click", function() { settings.datebox.style.display = "none"; settings.dateboxCover.style.display = "none"; }); } else { settings.dateboxCover.style.display = "block"; } var date = 0; if (settings.datefield.value === "") { date = new Date(); } else { date = new Date(settings.datefield.value); } settings.date.month = date.getMonth(); settings.date.day = date.getDate(); settings.date.year = date.getFullYear(); settings.date.startMonth = settings.date.month; settings.date.startYear = settings.date.year; view.showMonth(); }, showMonth: function () { var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var o = "<table>" + "<thead>" + "<tr>" + "<th data-click=\"prevMonth\"><</td>" + "<th colspan=\"5\">" + months[settings.date.month] + " " + settings.date.year + "</th>" + "<th data-click=\"nextMonth\">></th>" + "</tr>" + "<tr>" + "<th>Su</th><th>M</th><th>Tu</th><th>W</th><th>Th</th><th>F</th><th>Sa</th>" + "</tr" + "</thead><tbody>"; var n = new Date((settings.date.month+1) + "/1/" + settings.date.year); n.setDate(n.getDate() - n.getDay()); var m = n.getMonth(); var sm = n.getMonth(); while (m === sm || m === settings.date.month) { o += "<tr>"; for (var x = 0; x < 7; x++) { var d = n.getDate(); var y = n.getFullYear(); o += "<td"; if ( ((settings.date.startMonth + 1) + "/" + settings.date.day + "/" + settings.date.startYear) === ((m + 1) + "/" + d + "/" + y) ) { o += ' class="current"'; } if (m !== settings.date.month) { o += ' class="other"'; } o += " data-click=\"chooseDate\" data-date=\"" + (m + 1) + "/" + d + "/" + y + "\">" + d + "</td>"; n.setDate(n.getDate() + 1); m = n.getMonth(); } o += "</tr>"; } o += "</tbody></table>"; settings.datebox.innerHTML = o; var w = document.documentElement.clientWidth || document.body.clientWidth; settings.dateboxCover.style.width = w + "px"; settings.dateboxCover.style.height = document.body.scrollHeight + "px"; } }; var controller = { chooseDate: function (d) { settings.datefield.value = d; settings.datebox.style.display = "none"; settings.dateboxCover.style.display = "none"; }, dateboxClick: function(evt) { var click = evt.target.dataset.click; switch (click) { case "prevMonth": controller.prevMonth(); break; case "nextMonth": controller.nextMonth(); break; case "chooseDate": controller.chooseDate(evt.target.dataset.date); break; } }, nextMonth: function () { settings.date.month++; if (settings.date.month > 11) { settings.date.month = 0; settings.date.year++; } view.showMonth(); }, prevMonth: function () { settings.date.month--; if (settings.date.month < 0) { settings.date.month = 11; settings.date.year--; } view.showMonth(); } }; view.init(evt.target); }; var noTyping = function(evt) { evt.target.value = ""; }; var dates = document.getElementsByTagName("input"); for (var n = 0; n < dates.length; n++) { if (dates[n].dataset.input === "pickAdate") { dates[n].addEventListener("click", pickAdate); dates[n].addEventListener("input", noTyping); } } })();
CSS
div.pickAdateCover { background-color: #999; left: 0; opacity: .3; position: absolute; top: 0; z-index: 998; } div.pickAdate { background-color: #fff; border: 1px solid #000; color: #000; font-family: Verdana, Arial, Geneva, Helvetica, sans-serif; font-size: 12px; position: absolute; text-align: center; z-index: 999; } div.pickAdate table { border-spacing: 3px; } div.pickAdate table thead tr:nth-child(1) th { background-color: #cff; border: 1px solid #ccc; font-weight: bold; padding: 5px; } div.pickAdate table thead tr:nth-child(2) th { border: none; } div.pickAdate table tbody tr td { border: 1px solid #ccc; height: 20px; width: 20px; } div.pickAdate table tr td.current { background-color: #ff9; } div.pickAdate table tr td.other { background-color: #eee; color: #666; } div.pickAdate table th[data-click="nextMonth"], div.pickAdate table th[data-click="prevMonth"], div.pickAdate table td[data-click="chooseDate"] { cursor: pointer; }
HTML
<label>Enter a Date: <input type="text" data-input="pickAdate"></label>
Example:
-
-
Helpers
-
HTML
<label>Enter Numbers: <input type="text" data-input="numbersOnly"><label>
Javascript
var numbersOnly = function (evt) { evt.target.value = evt.target.value.replace(/\D/g,""); } var inputs = document.getElementsByTagName("input"); for (var n = 0; n < inputs.length; n++) { if (inputs[n].dataset.input === "numbersOnly") { inputs[n].addEventListener("input", numbersOnly); } }
-
To create a random number between 0 and 9, including 0 and 9.
Math.floor(Math.random()*10);
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.
-
function randomColor () { function randomHex () { return Math.floor(Math.random() * 16).toString(16); } return "#" + randomHex() + randomHex() + randomHex(); }
If you want to set a background color using this function just do the following:
document.getElementById("id").style.backgroundColor = randomColor();
-
function keyPress (e) { var evt = e ? e:event; var keynum = 0; if (window.event) { // IE keynum = evt.keyCode; } else if (evt.which) { // Netscape/Firefox/Opera keynum = evt.which; } alert(keynum); }
How to use: add to page js
document.onkeypress = keyPress;
Alert will pop up the key number that is coming in. If you want a specific key to do something, replace alert(keynum); in function keyPress with
if (keynum === number) { do something; }
If you want to see the character for the keynum, you could
String.fromCharCode(keynum)
-
window.onbeforeunload = function() { return "Leave this webpage?"; }
-
function findLeft (i) { var left = i.offsetLeft; while (i.offsetParent) { i = i.offsetParent; left += i.offsetLeft; } return left; } function findTop (i) { var top = i.offsetTop; while (i.offsetParent) { i = i.offsetParent; top += i.offsetTop; } return top; }
Example on how to call
divLeft = findLeft(document.getElementById("myDiv")); divTop = findTop(document.getElementById("myDiv"));
Finding the top left of an element on a webpage can be tricky. offsetLeft and offsetTop only give you the left and right of the element compared to its parent element. These functions help you walk back up all the parent elements and get the true left and top.
-
If someone asks you to write a Javascript function to reverse the text string in a text input, here is a workable answer.
Javascript
function reverseText (i) { var t = document.getElementById(i); var o = ""; for (var n = (t.value.length-1); n >= 0; n--) { o += t.value.charAt(n); } t.value = o; }
HTML
<input id="textField" type="text"> <input type="button" value="submit" onclick="reverseText('textField')">
-
-
Suggestions
- If you have trouble changing body color with javascript, it may be due to all your divs are position absolute, so the body has actually no area. Set width or height and your js call should start to work.
- When retrieving marginLeft etc., parseInt so the px part of the setting doesn't come through.
- Want to launch some javascript on page load -
window.onload = function() { javascript stuff }
or load an IIFE at the end of the page - When using parseInt, "08" and "09" will show up at 0 (zero) since base defaults to octal (base 8). Set second argument to 10 (decimal - base 10). To fix, use parseInt("08", 10);