JavaScript - auto-mate/CheatSheetWiki GitHub Wiki
ADO in JS
ADO - USE MSAccess in IE Javascript
Alert
Async
Bookmarklet POST TESTER
Browser Check
Cast
Centring Example
Class
Class Extend
Clipboard
Concatanate
Convert
Common Commands
Copy Element Text
Direct Download
Encyption
Event Listener
File Reading
getElementById
getElementsByTagName
Inject / Reload External Script
Insert Element
Image From String
Loop Objects
onclick
operators
ploty.js
POST TEST
Simple Ploty with MultiLayout Change and DataChange
Run Script That Belongs to a Frame
Scroll and Set Interval
Speech
Update Object
XHTML
console.clear()
original = { a: 1, b: 2 };
adiitionsAndChanges = { b: 34, c: 75 };
Object.assign( original, adiitionsAndChanges );
// Original Has "a" as is, "b" updated to 34 and "c" added
console.log( original );
document.iframeResult.window.myFunction()
[runs myFunction from browser console when its in an iframe called "iframeResult"]
Not Just JavaScript but [ U S E % N O T * ] when using LIKE in Access even if query saved in Access!
**** Get Recordset from MSAccess as Javascript Array For File "C:\FolderA\FolderB\..\...DatabaseName.accdb" And PASSWORD='password' [IE Only]
function ReadAccess(sql) {var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
try {adoConn.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\\FolderA\\FolderB..\\..\\DatabaseName.accdb';Jet OLEDB:Database Password='password'");}
catch(err) {alert(err + "Login Error");}
adoRS.Open(sql, adoConn, 1, 3);
var fc = adoRS.Fields.Count;
ds=[];
while (adoRS.EOF==false)
{rs=[];
for (i=0;i<fc;i++)
{rc=adoRS.Fields(i).value.toString();
rs.push(rc);
}
ds.push(rs);
adoRS.moveNext();
}
adoRS.Close();
adoConn.Close();
return ds;
}
Use +
alert('SomeText');
document.getElementById("idName").innerHTML="New Value";
var SomeVar1=document.getElementById("idName").innerHTML;
var SomeVar2=document.getElementById("idName");
Below returns and object of the styles in the first DIV
document.getElementsByTagName("DIV")[0].style
Below returns how many DIV's
document.getElementsByTagName("DIV").length
Below writes DIV's contents to console via debug
for (i=0;i<document.getElementsByTagName("DIV").length;i++) {console.debug(document.getElementsByTagName("DIV") [i].innerHTML);}
&& And
|| Or
! Not
== Equals
e.g. in <button
onclick="function('Value For function')"
onclick="Alert('Hello World')"
function StartScroll() {
scrollTimer=setInterval(function() {
var n=window.pageYOffset;
window.scrollBy(0, 1);
if (n==window.pageYOffset)
{window.scrollTo(0, 0);}},100);
}
function ClearScroll() {
clearInterval(scrollTimer);
}
<!DOCTYPE html>
<html>
<head>
<style>
.lw {
width:400px;
display:inline-block;
height:400px;
margin:5px;
}
</style>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body style="background-color:blue;">
<div id="id6" class=""></div>
<div id="id5" class="lw"></div>
<div id="id4" class="lw"></div>
<div id="id3" class="lw"></div>
<div id="id2" class="lw"></div>
<div id="id1" class="lw"></div>
<script>
// Bubble
Plotly.newPlot( 'id1', [{
x: [1, 2, 3, 4, 5],
y: [1, 2, 4, 8, 16],
marker:{opacity:0.4,color:['red','blue'],size:[10,20,30,40,50],mode:'markers'}}],
{margin: { t: 0 },plot_bgcolor: 'lightblue',paper_bgcolor: 'darkblue',font:{color:'#FFF'}});
// Line
TEST = document.getElementById('id2');
Plotly.plot( TEST, [{
x: [1, 2, 3, 4, 5],
y: [1, 2, 4, 8, 16] }],
{margin: { t: 0 } } );
// Bar
Plotly.plot( 'id3', [{
x: [1, 2, 3, 4, 5],
y: [1, 2, 4, 8, 16],type:'bar'}], {
margin: { t: 0 } } );
// Grouped Bar
var trace1 = {
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
name: 'SF Zoo',
type: 'bar'
};
var trace2 = {
x: ['giraffes', 'orangutans', 'monkeys'],
y: [12, 18, 29],
name: 'LA Zoo',
type: 'bar'
};
var data = [trace1, trace2];
var layout = {barmode: 'group'};
Plotly.newPlot('id4', data, layout);
//Stacked Bar
var trace1 = {
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
name: 'SF Zoo',
type: 'bar'
};
var trace2 = {
x: ['giraffes', 'orangutans', 'monkeys'],
y: [12, 18, 29],
name: 'LA Zoo',
type: 'bar'
};
var data = [trace1, trace2];
var layout = {barmode: 'stack'};
Plotly.newPlot('id5', data, layout);
Plotly.d3.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv', function
(err, rows){
function unpack(rows, key) {
return rows.map(function(row) { return row[key]; });
}
var data = [{
type: 'choropleth',
locationmode: 'USA-states',
locations: unpack(rows, 'code'),
z: unpack(rows, 'total exports'),
text: unpack(rows, 'state'),
zmin: 0,
zmax: 17000,
colorscale: [
[0, 'rgb(242,240,247)'], [0.2, 'rgb(218,218,235)'],
[0.4, 'rgb(188,189,220)'], [0.6, 'rgb(158,154,200)'],
[0.8, 'rgb(117,107,177)'], [1, 'rgb(84,39,143)']
],
colorbar: {
title: 'Millions USD',
thickness: 0.2
},
marker: {
line:{
color: 'rgb(255,255,255)',
width: 2
}
}
}];
var layout = {
title: '2011 US Agriculture Exports by State',
geo:{
scope: 'usa',
showlakes: true,
lakecolor: 'rgb(255,255,255)'
}
};
Plotly.plot('id6', data, layout, {showLink: false});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.lw {
width:400px;
display:inline-block;
height:400px;
margin:15px;
}
</style>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body style="background-color:black;">
<div id="id1" class="lw"></div>
<script>
xdataAH=[1,2,3,4,5];
ydataAH=[1,2,3,4,5];
// Bar
Plotly.plot( 'id1', [{
x: [1, 2, 3, 4, 5],
y: [1, 2, 4, 8, 16],type:'line'}],{xaxis:{title:'orig'},
updatemenus: [{
y: 0.8,
yanchor: 'top',
buttons: [
{
method: 'restyle',
args: ['line.color','red'],
label: 'red'
},
{
method: 'restyle',
args: [{'line.dash':'dot','line.color': 'green'}],
label: 'green dots'
},
{
method: 'update',
args: [{type:'bar'}],
label: 'new type'
}]
},
{
y:1,
yanchor: 'top',
buttons: [
{
method: 'restyle',
//args: [{x: [[1, 2, 3, 4, 5]],y:[[1,2,3,4,5]]}],
args: [{x:[xdataAH],y:[ydataAH]}],
label: 'new data?'
}
]
}
]}
);
function custom() {
alert('OK')
}
</script>
</body>
</html>
function AddScript(ref,message) {
/*
** Removes any existing script marked with "ref" at char 4
** Adds a script marks it with [ref] which shows message [message]
** The script will run when appended
*/
//Set Flag To Alert Removal Required
rem = false;
// Get all the Scripts in the Body
scriptTags = document.body.getElementsByTagName("SCRIPT");
// Loop Scripts in the Body to find one with "ref" at the begining - if found set remove flag and exit
for ( n=0 ; n < scriptTags.length ; n++ ) {
if ( scriptTags[n].text.substr(4,3) == "ref" ) {
rem = true;
break;
}
}
// if remove flag set remove script
if ( rem == true ) { document.body.getElementsByTagName("SCRIPT")[n].remove(); }
// Create and append new script
el = document.createElement("SCRIPT");
el.text = "\r\n//ref " + ref + "\r\n" + "alert('"+message+"');" + "\r\n";
document.body.appendChild(el);
}
function testPost( webUrl, postDataKeyNameValuePairs ) {
f=document.createElement( "form" );
f.method = "post";
f.action = webUrl;
f.style.visibility = "hidden";
for ( elem in postDataKeyNameValuePairs ) {
i = document.createElement ( "input" );
i.name = elem;
i.value = postDataKeyNameValuePairs[ elem ];
f.appendChild( i );
}
s = document.createElement ( "input" );
s.type = "submit";
f.appendChild ( s );
document.body.appendChild ( f );
f.submit ();
}
testPost ( "TEST.php" , {t1:'v1',t2:'v2',t3:3} );
// OR Run in chromium-browser --disable-web-security --user-data-dir="<some directory here>"
let res="";
const xReq = new XMLHttpRequest();
xReq.onload = function(d) {
res=d
alert(res)
}
xReq.open("POST", "<address>", true); // true/false for async also can add user,pass
xReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xReq.send("p1=v1&p2=v2");
javascript:
function testPost() {
var webUrl=prompt("enter webUrl","https://www.w3schools.com/php/welcome.php");
var postDataKeyNameValuePairsStr=prompt("enter JSON KeyNameValuePairs","{\"name\":\"ME\",\"email\":\"eME\"}");
postDataKeyNameValuePairs=JSON.parse(postDataKeyNameValuePairsStr);
f=document.createElement( "form" );
f.method = "post";
f.action = webUrl; f.style.visibility="hidden";
for (elem in postDataKeyNameValuePairs) {
i=document.createElement( "input" );
i.name = elem;
i.value = postDataKeyNameValuePairs[elem];
f.appendChild( i ); }
s=document.createElement( "input" );
s.type = "submit";
f.appendChild( s );
document.body.appendChild( f );
f.submit();
}
testPost();
The blow will replace an existing script and force a reload. This does not work if you try reinserting "OldScript" creation and insertion of a new element with document.createElement("script") is required for it to work.
OldScript = document.getElementsByTagName("SCRIPT")[0];
src = OldScript.src;
NewScript = document.createElement("script");
NewScript.src = src;
OldScript.remove();
document.getElementsByTagName("HEAD")[0].appendChild(NewScript);
/* PHP Based Example For png File */
echo "<img id='lbl' src='' >";
echo "<script>
document.getElementById('lbl').src = \"data:image/png;base64," . base64_encode($ImageStringPng) . "\";
</script>";
parseInt("") and parseFloat("") convert string to value.
/* On paste to this cell runs input(). input() Expects data as a table cols tab delimited \t and rows new line delimited \n */
<td onpaste ="input(event,this)" contenteditable = "true">1</td>
<script>
function input(e,el) {
// stop normal paste
e.preventDefault();
// get data into array of rows, each row an array of columns
var cData = e.clipboardData.getData('text').split("\n").map(x=>x.split("\t"));
// irrelevant loop
for ( i = 0; i < cData.length ; i++ ) {
for ( j = 0; j < cData[i].length ; j++ ) {
a=1;
}
}
}
</script>
function centreSTD() {
leftExtra = ( window.innerWidth - ( /*< ACTUAL WIDTH >*/ ))/2;
topExtra = ( window.innerHeight - ( /*< ACTUAL HEIGHT >*/))/2;
if ( leftExtra <= 0 ) { leftExtra = 0; }
if ( topExtra <= 0 ) { topExtra = 0; }
document.getElementById("/*<Id of pos:absolute Div Holding Whole Page>*/").style.left = leftExtra + "px";
document.getElementById("/*<Id of pos:absolute Div Holding Whole Page>*/").style.top = topExtra + "px";
}
window.onresize = centreSTD;
window.onload = centreSTD; // same as <body onload="centreSTD();" >
<!doctype html>
<html>
<body>
<button onclick = "ReadThis('Hello')" >Speak</button>
<script>
voice = speechSynthesis.getVoices(); // Load first time is error so loaded here , gets 1st time out of the way!
function ReadThis(ReadString) {
// Send text here chops into new line lengths (stops 15 second bug)
// Added ". " To allow pause.
stringArray = ReadString.split("\n")
stringCount = stringArray.length
for ( i=0 ; i < stringCount ; i++ ) {
if (stringArray[i].trim() != "") {
SayStuff(stringArray[i]+". ")
}
}
}
function SayStuff(toRead) {
// Cant Speek unless User Runs a command !!
syn = window.speechSynthesis;
say = new SpeechSynthesisUtterance()
voice = syn.getVoices()[5]; // get all voices but pick no 5
say.voice = voice;
say.text = toRead;
syn.speak(say);
}
</script>
</body>
</html>
var fileContent = "Some Data";
var blob = new Blob([fileContent ], { type: 'text/plain' });
var link = document.createElement('a');
link.download = 'download.txt';
link.href = window.URL.createObjectURL(blob);
link.click();
NB # in front of function e.g. #multiply(a,b) makes function private (same for field)
can use static in front of function
//Make Class Template
class ah1 {
// need min of
// constructor() { }
constructor(x,y) {
this.x = x;
this.y = x;
}
// NB dont need function prefix
///////////////////////////////
a() {return "this.x = " + this.x;}
// can define method as static if required to stop duplication (not shown)
//////////////////////////////////////////////////////////////////////////
b() {return "this.y = " + this.y;}
c(newData) {return "newData = " + newData;}
d() {
// field can be private e.g. txt change to #txt
///////////////////////////////////////////////
let txt = "OK;
}
}
//Create instance as n
n = new ah1("aaa","bbb");
// execute function a of our instance to return "this.x = aaa" to variable out1
out1 = n.a();
// this.x = aaa
// execute function b of our instance to return per below to variable out2
out2 = n.b();
// this.y = bbb
// execute function c of our instance to return per below to variable out3
out3 = n.c("somedata");
// newData = somedata
// EXTENDING CLASSES
// Keywords **** extends and **** super()
// Class can include non class types e.g. add NonClassObectBeast to a class called dog
// via command Object.setPrototypeOf(Dog.prototype, NonClassObectBeast); This is not in the class but before usage.
class sandwich {
constructor(bread) {
this.bread = bread;
}
breadType() {
return 'Use ' + this.bread + ' bread';
}
}
class filling extends sandwich { // ****
constructor(bread, filling) {
super(bread);// **** Call parent constructor with brand as input into model
this.filling = filling;
}
description() {
return this.breadType() + ', with ' + this.filling;
}
}
let myButtie = new filling("brown", "tuna");
console.log(myButtie.description());
Can use for debug as below...
function sendDataAH( address, postDataAmpSep ) {
//ADD var_dump($_POST); to top of php file to send back what it recieved if required
// EG postDataAmpSep = sendDataAH("../SOMEFILE.php" , "x[]=1&x[]=2&y[]=a&y[]=b&y[]=c") // SEND arrays
// EG postDataAmpSep = sendDataAH("../SOMEFILE.php" , "x=1&y=2") // SEND individual values
// EG address = "../SOMEFILE.php"
// Action on load
// ADD A DEBUG ELEMENT WITH id = "debug" to use the bloew
/*
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
*/
//Make New OBJ
xhttp = new XMLHttpRequest();
xhttp.open("POST", address, true); // true re async or not
// For Form
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
// CAN BE USED FOR JSON ETC
//xhttp.setRequestHeader("Content-type", "application/json");
// Send with POST Data
xhttp.send( postDataAmpSep );
}
Cheap and cheerful....
if ( typeof( navigator.userAgentData ) == "object" ) {
if ( !( navigator.userAgentData.brands[2].brand == "Microsoft Edge" || navigator.userAgentData.brands[2].brand == "Google Chrome" ) ) {
alert("Your Browser is not supported use Chrome or Modern Edge Browsers");
}
} else {
alert("Your Browser is not supported use Chrome or Modern Edge Browsers ");
}
Add to either document as here or to an element.
Parameters for addEventListener( 1 = event, 2 = function, 3 = optional bool |capturing true or bubbling phase false | )
Prrameter 1. the action to listen for: e.g. "keypress"
abort, afterprint, animationend, animationiteration, animationstart,
beforeprint, beforeunload, blur
canplay, canplaythrough, change, click, contextmenu, copy, cut
dblclick, drag, dragend, dragenter, dragleave, dragover, dragstart, drop, durationchange
ended, error,
focus, focusin, focusout, fullscreenchange, fullscreenerror,
hashchange, input, invalid, keydown, keypress, keyup
load, loadeddata, loadedmetadata, loadstart
message, mousedown, mouseenter, mouseleave, mousemove, mouseover, mouseout, mouseup, mousewheel
offline, online, open,
pagehide, pageshow, paste, pause, play, playing, popstate, progress
ratechange, resize, reset, scroll, search, seeked, seeking, select, show, stalled, storage, submit, suspend
timeupdate, toggle, touchcancel, touchend, touchmove, touchstart, transitionend
unload,
volumechange
waiting, wheel
- Name of the function
e.g. externalFunc
- true/false
true = on event
false = on bubbling
Sample Code
// Use an External Function else you can't remove
// Create function for example
function externalFunc() { console.log( "From Listener" ); }
// add listener
document.addEventListener( "keydown", externalFunc, true );
// remove if required listener
document.removeEventListener( "keydown", externalFunc, true );
Options 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.
<Some_New_Element> = document.createElement("div");
document.getElementById("<Some_Existing_Element>").insertAdjacentElement("afterEnd",<Some_New_Element>)
function copy(id) {
window.getSelection().selectAllChildren(
document.getElementById(id)
);
document.execCommand('copy');
}
STR = "";
for (let <SOME_VAR> in <SOME_OBJECT>) {
STR += <SOME_OBJECT>[<SOME_VAR>].<SOME_NAME_OF_ITEM>;
}
// Ex 1
async function w3() {
return 10;
}
async function af() {
await w3().then(
function(value) { console.debug(value) },
function(error) { console.debug(error) }
)
console.debug("OK")
}
af()
// Ex 2
async function w32() {
return 20;
}
async function af2() {
await w32().then(
function(value) { OK(value) },
function(error) { er(error) }
)
console.debug("OK")
}
function OK(v) {console.debug("OK " + v)}
function er(v) {console.debug("Er " + v)}
af2()
The Html library:
<script src="sodium.js"></script>
Code to encrypt hello world form an element with onclick="sendCrypt(event)"
function sendCrypt(event) {
event.preventDefault();
if ( window.document.readyState != "complete" ) {
alert( "Please try again in a moment");
return;
}
let key = sodium.crypto_secretbox_keygen()
let message = "Hello World"
let nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
let cryptMessage = sodium.crypto_secretbox_easy(message,nonce,key);
console.debug(nonce)
console.debug(cryptMessage)
let decryptMessageBytes = sodium.crypto_secretbox_open_easy(cryptMessage,nonce,key);
let decryptMessage = sodium.to_string(decryptMessageBytes)
// send the nonce with the encrypted message if required
// keep the key (make sure nonce is available somewhere does not need to be encrypted )
console.debug(decryptMessage)
}
Html for the user to select a file to read.
<form method="post">
<input type="file" id="fileToRead">
<input type="submit" onclick="readFile(event)">
</form>
function to read the file when
<script>
function readFile(event) {
event.preventDefault();
// NB can only read a file selected by user
fReader = new FileReader();
fileData = document.getElementById("fileToRead").files[0];
fReader = new FileReader();
fReader.readAsBinaryString( fileData ); // can read as array Array Buffer,DataUrl,and Text
showFileContent();
}
function showFileContent() {
if (fReader.readyState == 2) {
alert(fReader.result);
} else {
setTimeout(function() {showFileContent()},500);
}
}
</script>