Cool JavaScript
🖥
🖥

JavaScript can change the source of an HTML <img>

Show the first image. Give it an id=" "<img id="coin" src="... ">
Then write a javascript definition...
<script>
  let coinDisplay = document.getElementById("coin");
</script>
Then use HTML Buttons to alter the parameters...
<button type="button" class="entry" onclick="coinDisplay.src='1917d-ob-sm.png' ">Heads</button>
<button type="button" class="clear" onclick="coinDisplay.src='1917d-re-sm.png' ">Tails</button>
CSS Styling Reference
Outputbox
.entry { width: 150px; height: 30px; background-image: -webkit-linear-gradient(80deg, #008080, #000000, #008080); color: #ecd8b8; border-radius: 15px; font-weight: bold; font-size: 14px; }

.clear { width: 150px; height: 30px; background-image: -webkit-linear-gradient(80deg, #ff0000, #ff0000, #000000, #ff0000, #ff0000); color: #ffffff; border-radius: 15px; font-weight: bold; font-size: 14px; }

.outputbox { width: 300px; height: 24px; background-image: -webkit-linear-gradient(80deg, #008080, #000000, #008080); color: #ecd8b8; margin: 0 auto; border: 2px solid #ff9d80; line-height: 24px; margin-bottom: 8px; }

Basics
JavaScript goes between HTML <script> javascript here </script> tags

HTML Buttons can execute javascript functions:
<button type="button" onclick="functionName()" >Button Text</button>

Bracket Types
( ) Round Brackets (parenthesis) process variables
[ ]Square Brackets are used for arrays
{ }Curly Brackets (braces) contain javascript code
Comments
// Comments follow two forward slashes on one line
/* Comments written between these */ , are useful for multiline comments
As in HTML, CSS, and SVG, JavaScript ignores multiple spaces, tabs, and line feeds
Statements
Semicolons ; MUST end all JavaScript statements.
Multiple statements on one line are allowed when each statement is separated by a semicolon.

let a = 5;let b = 6.33;let c = a + b;

Declaring Variables - const, let
Variables MUST be declared before they can be used.

const a = 3 ; // Constants MUST be given a value when they are declared
const a = [1,"a"] ; // Arrays MUST be given a value when they are declared
let a = 3 ; // declares a Variable and assigns a value
let a ; // declares a Variable
var a = 3 ; // this is older code DO NOT USE 'var'

JavaScript Variables that are declared outside of any function() or block { }
are Global Scope Variables that any function can access.
Identifiers
JavaScript identifiers are case sensitive
Hyphens are NOT allowed in JavaScript. Hyphens are reserved for subtraction only

The Best Practice for Identifiers is to use cameLcase which starts with a lowercase letter. Examples are:
firstName, lastName, visaCard, phoneNumber, expDate

let lastname, lastName;// declares 2 different variables
lastname = "Doe";// assigns a string to lastname
lastName = "Lincoln";// assigns a string to lastName

= assigns a value to a variable (NOT an equal sign)
This expression is valid in JavaScript:   x = x + 5// adds 5 to x  (same as x += 5)

Using Functions
Function code template...

<script>
function functionName() {
  // block of code to be executed
}
</script>

Function code example...

<script>
function myRoulette() {
  wheelNum = Math.floor(Math.random() * 38);
  if (wheelNum > 36) {wheelNum = "00";}
  document.getElementById("wHeel").innerHTML = wheelNum ;
}
</script>

A function can be called called using...
onClick
<button type="button" onclick="myRoulette()" >Run Function</button>
onmouseover
<div onmouseover="myRoulette()" >div element</div>
'Streamlining' Javascript Code
Since the folowing code is used a lot, declare it as a variable:

<script>
let myDiv = document.getElementById("someDiv") ;
</script>
Then it can be accessed so:

myDiv.innerHTML = "some text" + numbers ;// outputs to the div

myDiv.innerHTML = "" ;// clears the div

Display as Currency

myDiv = document.getElementById("someDiv") ;
let x ;
x = (x).toFixed(2) ;

myDiv.innerHTML = "$  " + x ;

Output Methods
.innerHTML
<script>
document.getElementById("display1").innerHTML = (15 + 6) + " is the answer" ;
</script>
Math can also be performed with .innerHTML. The above result...

The above box is a <p> element with a border, assigned a class, and given an id

The box below is a <div> styled by a CSS class named .outputbox and assigned an id.

emoji display using .innerHTML=
😊 (&#x1f60a;)
Replace the &#x with 0x (no semicolon at end)
Treat the emoji code as a variable with no quotes
.innerHTML = String.fromCodePoint(0x1f60a) + " Input must be a positive number less than 1";

Using a <span> in Javascript
DO NOT USE <span> for .innerHTML directly inside <button> tags
<span> tags must be inserted between quotes in the output string, the same as text.

Use single quotes for the CSS style = 'definitions'.

<script>
ans1 = "<span class = 'red'>" + "The answer is " + "</span>" ;
ans2 = "&radic;" + "<span style = 'text-decoration: overline;'>" + " 2 " + "</span>" + " = 1.414" ;

OR

ans1 = "<span class = 'red'>The answer is </span>" ; // shorter version
ans2 = "&radic;<span style = 'text-decoration: overline;'> 2 </span> = 1.414" ; // shorter version
</script>

Fot the .innerHTML output, use the variables:   myDiv.innerHTML = ans1 + ans2 ;

print

<button type="button" class="entry" onclick="print()">Print this page</button>

Input Methods & Alerts
Be Careful

The Alert() Method may be called alone OR within a function

Internal text formatting can be tricky

Also they can be annoying — use sparingly

Stand Alone
<script>
function myAlert() {
  alert("The alert can also perform math: 15 + 6 = " + (15 + 6) ) ;
}
</script>

<button type="button" class="entry" onclick="myAlert()">Alert Box</button>

Error Checking Code with Alert
<script>
function myFunction() {
    if( (x < 0) || (x >= 1) ) { document.getElementById("answerBox").innerHTML = "Input must be a positive number less than 1" ; }

    else if(isNaN(y)) {
    alert("NOT a number! Try again." ) ;
    document.getElementById("answerBox").innerHTML = "&quot;" + x + "&quot; is NOT a number. Input MUST be a number." ; }

    else { All remaining javaScript code . . . }
</script>

Input via Alert Box
let person = prompt("Please enter your first name:", "default answer" ) ;

Input via Confirm Box
let answer = confirm("Proceed with deposit?") ;// returns true or false

Input via Standard Text Box

<input type="text" id="textBox" value=" default text, if any" >   // standard box, no class defined

<script>
function textboxFunction() {
let x = document.getElementById("textBox").value;   // retrieves the value displayed
  document.getElementById("textOut").innerHTML = x;

}
</script>


Input via Standard Number Box
NOTE: type="number" comes with up ⁄ down buttons

<input type="number" id="numBox" value="3.14159265358">

<script>
function numberFunction() {
let x = document.getElementById("numBox").value;   // retrieves the value displayed
  document.getElementById("numOut").innerHTML = x;

}
</script>



if   else   else if   and   or
if() { }   else { }   else if() { }
if (condition) {
  // block of code to execute if the condition is true
} else if (condition2) {
  // block of code to execute if condition2 is true
} else {
  // block of code to execute if the condition is false

else if and else are optional

Logic Conditionals:
The (condition) MUST be inside ( ). Options are:

==is equal to
>=is greater than or equal to
<=is less than or equal to
!=is not equal to
+=adds/concatenates the right side to the left side
&&and, compares two values, if both are true returns true
||or, compares two values, if either is true returns true

Example:
<script>
  let x;
  let ans = "the number is positive";
if (x == 0) {
    ans = "the number is zero";

else if (x < 0) {
    ans = "the number is negative";

  }
</script>
Arrays

<script>
const arr = [ "Tesla",1,3,5,7,9 ] ;
</script>

Array Elements by Index Number
Array elements are indexed starting at 0

<script>
const arr = [ "Tesla" ,2,4,6,8 ] ;
let x = arr[0] ;    // returns x = Tesla
let y = arr[1] ;    // returns y = 2
</script>

array.includes() Method
To determine if an array contains a term use the Method array.includes()

<script>
const arr = [ "Tesla" ,1,3,5,7,9 ] ;
let termx = "Tesla";
if ( arr.includes(termx) ) {
  // if termx is in the array, returns true, then do something
}
</script>

To use a term in an array by index number

<script>
const arr = [ "Tesla" ,1,3,5,7,9 ] ;
let termx = arr[ 0 ];
  // do something using Tesla
</script>

Modify an Array
array.push() Method   array.pop() Method

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"] ;
fruits.push("Kiwi"); document.getElementById("idName").innerHTML = fruits;
fruits.pop("Apple"); document.getElementById("idName").innerHTML = fruits;
</script>

Result...

fruits = ["Banana", "Orange", "Mango", "Kiwi"] ;   // "Kiwi" added with push(), "Apple" removed with pop()
Sorting an Array
array.sort() Method   array.reverse() Method

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango", 2, 3, 1] ;
fruits.sort(); document.getElementById("idName").innerHTML = fruits;
fruits.reverse(); document.getElementById("idName").innerHTML = fruits;
</script>

Results...

1) fruits = [1,2,3,"Banana","Kiwi","Mango","Orange"] ;   // first sorts alphabetically
2) fruits = ["Orange","Mango","Kiwi","Banana",3,2,1] ;   // then reverse sorts
Sorting Numbers in an Array
array.sort( function(a, b) {return a - b} )

<script>

const points = [40, 100, 1, 5, 25, 10] ;
points.sort( function(a, b) {return a - b} ); document.getElementById("idName").innerHTML = points;
points.reverse() ); document.getElementById("idName").innerHTML = points;
</script>

Results...

1) points = [1, 5, 10, 25, 40, 100] ;   // first sorts ascending
2) points = [100, 40, 25, 10, 5, 1] ;   // then sorts descending
Loops
<script>
for (let i = 0; i < 10; i++) {   // i from 0 to 9 increment +1
  if (i == 3) { break; }// { break; } stops the for loop when i=3 (optional)
  /* javascript code to execute */
}
</script>
When looping through any Array replace the actual length with arrayName.length

Unicode Characters in Text
Unicode Formats - always put in "quotes"
escape Unicode:  " \u00a9 "
extended Unicode: " &#x1fa90; "

<script>
// source array
let specialChars = ["\u00a9","\u2609","\u0394","\u03c0","\u21e9","\u2014","&#x130ba;","&#x13080;",
"&&#x130ba;","&#x1305c;","&#x1fa90;","\u2780","\u279C","\u25ba","\u2614","&#x1f1fa;&#x1f1f8;",
"&#x1f5fa;","&#x1f488;","&Oslash;"
] ;

function showChars() {
document.getElementById("unicodeBox").innerHTML = ""; // 1st clear the box
  for (let i = 0; i < specialChars.length; i++) {
  document.getElementById("unicodeBox").innerHtml += specialChars[ i ] + " " ;
  }
}
</script>

Sample Unicode Characters

Egyptian Hieroglyphics Unicode Travel & Places

∫ ƒ(x) dx Mathematics

Math Calculations
Math.round()Rounds up(4.5) returns 5
Math.floor()Rounds down(4.5) returns 4
Math.ceil()Rounds up next integer(4.1) returns 5
Math.trunc()Removes decimal part(4.1) returns 4
Math.sign()Returns 1, 0, -1(4.5) returns 1,  (-4.5) returns -1,  (0) returns 0
Math.abs()Absolute Value(4.5) returns 4.5,  (-4.5) returns 4.5,  (0) returns 0
x.toFixed(n)x to n decimal places(n) returns x to n decimal places, rounded up
Math.PIpi πreturns 3.141592653589793...
Math.PI.toFixed(5)pi to 5 decimal placesreturns 3.14159
Math.EEuler's number ereturns 2.718281828459045...
Math.E.toFixed(5)e to 5 decimal placesreturns 2.71828
Φ = ( 1 + √5  ) ⁄ 2Φ Golden Ratio returns 1.618033988749895...
1 ⁄ ΦInverse Golden Ratio returns 0.618033988749895...
Math.SQRT22returns 1.4142135623730951...
Math.SQRT1_22 ⁄ 2returns 0.7071067811865476... sin(45°) = cos(45°)
Math.sin(θ)Returns sine(θ in radians) returns sine of angle θ
Math.cos(θ)Returns cosine(θ in radians) returns cosine of angle θ
Math.tan(θ)Returns tangent(θ in radians) returns tangent of angle θ
Math.asin(n)Returns arcsine(n) returns angle θ in radians
Math.atan(n)Returns arctangent(n) returns angle θ in radians
Number.isInteger(x)Returns true or falseuseful in if () {   } statements
Arithmetic Operators
JavaScript uses the basic arithmetic operators ( + - * / ) plus these...

** Exponentiation y = x ** 2
**Exponentiation (square root)y = x ** .5x
**Exponentiation (more roots)y = x ** (1/3)3x  cube root of x
++Incrementx = x++adds 1 to x
--Decrementx = x--subtracts 1 from x
+=Concatenate1x += yconcatenates y to x  useful for strings in loops
%Modulus (division remainder)x = 5 % 2returns 1   (5 ÷ 2 = 2 with remainder of 1)

For the Operation: y = 2 ** .5 ;can also be written: y = x ** (1/2) ;

1 Concatenate - link together in a series, append to, from the Latin: concatenat

Radians ⭤ Degrees
degrees = (180 / π) x (radians)       radians = (π / 180) x (degrees)
Φ Phi

Quadratic Equations
ax² + bx + c = 0
The Quadratic Equation is a second order equation
and therefore has
two solutions (roots) given by:

x = -b ± b² - 4ac
        2a          

where a ≠ 0
𝒾 = √ -1 

Drawing Canvas
Output to a Drawing Canvas
Define a Drawing Canvas
<canvas id="myCanvas" width="960" height="500" style="background-color: #000000; border: 1px solid #00cccc;" >
</canvas>
Canvas Origin (0,0) is the upper left corner   x →   y ↓

    Correct Order of <script> Sequencing...
  1. Access the canvas with ctx
  2. ctx.beginPath();
  3. set parameters - ctx.lineWith = 4; , ctx.strokeStyle = ("#123456"); , ctx.fillStyle = ("#123456");
  4. enter type of path - moveTo(x0,y0); lineTo(x1,y1);   rect(x0,y0,x1,y1);   arc(x,y,r,0,2*Math.PI);
  5. ctx.stroke();
  6. ctx.fill();
Canvas - Add a Line
<script>
let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d") ;
ctx.beginPath() ;
ctx.lineWidth=4 ;
ctx.strokeStyle=("#00ffff") ;
ctx.moveTo(0, 0) ;
ctx.lineTo(300, 150) ;
ctx.stroke() ;
</script>
Canvas - Draw a Dashed Line
ctx.setLineDash([10, 5]) ;   // dashes are 10px and spaces are 5px
Canvas - Draw a Rectangle
<script>
let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d") ;
ctx.beginPath() ;
ctx.lineWidth=4 ;
ctx.strokeStyle=("#00ffff") ;
ctx.fillStyle=("#ff0000") ;
ctx.rect(20, 20, 150, 100) ;// Start co-ords, x width, y height
ctx.stroke() ;
ctx.fill() ;
</script>
Canvas - Draw an Arc or Circle
ctx.arc(x center coord, y center coord, radius, start angle, end angle, direction) ;
direction is optional, false is default (clockwise), true is counter clockwise
Complete circle: 02*Math.PI
<script>
let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d") ;
ctx.beginPath() ;
ctx.lineWidth=4 ;
ctx.strokeStyle=("#00ffff") ;
ctx.fillStyle=("#ff0000") ;
ctx.arc(100, 75, 50, 0, 2 * Math.PI) ;
// center co-ords, radius, start angle, end angle
ctx.stroke() ;
ctx.fill() ;
</script>
Canvas - Linear Gradient Fill
<script>
let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d") ;
let grd = ctx.createLinearGradient(x0,y0,x1,y1) ;
grd.addColorStop(0, "green");
grd.addColorStop(1, "blue");
ctx.beginPath() ;
ctx.lineWidth= 4 ;
ctx.strokeStyle=("#00ffff") ;
ctx.fillStyle= grd ;
ctx.rect(20, 20, 150, 100) ;// define rectangle x0,y0 to x1,y1
ctx.stroke() ;// draw rectangle
ctx.fill() ;// fill any closed shape
</script>
Canvas - Add Text
Text is anchored at its lower left corner
<script>
let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d") ;
ctx.fillStyle=("#ff0000") ;// color of text
ctx.font = "16px arial" ;
ctx.fillText("Betelgeuse",345,30) ;// Text, x coord, y coord
</script>
Canvas - Add Shadows
<script>
let c = document.getElementById("myCanvas") ;
let ctx = c.getContext("2d") ;
ctx.fillStyle=("#ff0000") ;
ctx.shadowBlur= 2 ;// Blur factor of shadow
ctx.shadowOffsetX= 1 ;// X offset of shadow
ctx.shadowOffsetY= 1 ;// Y offset of shadow
ctx.shadowColor=("#ff0000") ;// color of shadow, default is black
ctx.rect(20, 20, 150, 100) ;// draws a rectangle with a shadow
ctx.font = "16px arial" ;
ctx.fillText("Betelgeuse",345,30) ;// writes text with a shadow
</script>
Clear the Canvas
<script>
function clearField() {
const context = myCanvas.getContext('2d') ;
context.clearRect(0, 0, 960, 500) ;
}
</script>
Dates / Time
d = new Date();
<script>
const d = new Date() ;
document .getElementById("dateBox").innerHTML = d ;   // default format
</script>

<script>
function getDate() {
const d = new Date() ;
const months = [
  "January","February","March","April","May","June","July","August","September","October","November","December" ] ;
const weekDays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] ;
let year = d.getFullYear() ;
let month = months[d.getMonth()] ;
let day = d.getDate() ;
let weekDay = weekDays[d.getDay()] ;
document.getElementById("dateBox").innerHTML = weekDay + ", " + month + " " + day + ", " + year ;
}
</script>

Time Display

<script>
let intervalID; // global variable to store the unique intervalID

function startTime() {
intervalID = setInterval(getTimer,1000) ; // begins the intervals for calling "getTimer" function
}

function getTimer() {
const d = new Date() ;
let h = d.getHours() ;
if (h > 12) { h = h - 12; }; // change to 12 hour clock
let s = d.getSeconds() ;
if (s < 10) { s = "0" + s; } ; // change to 2 digit seconds display
let m = d.getMinutes() ;
if (m < 10) { m = "0" + m; } ; // change to 2 digit minutes display
document.getElementById("timeBox").innerHTML = h + ":" + m + ":" + s ;
}

function stopTimer() { // clears the intervalID, therefore stops calling the "getTimer" function
clearInterval(intervalID) ;
document.getElementById("timeBox").innerHTML = "";
}
</script>

Typewriter Text
<script>
let i = 0 ;

function typeWriter() {
txt = '1717... somewhere in the Caribbean...' ; // text to type
let speed = 100 ;
if (i == 0) { document.getElementById("typing").innerHTML = "" ; } // clears "typing" at i = 0
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i) ;
i++;
setTimeout(typeWriter, speed) ;
}
else { i = 0; } // resets the counter for additional button clicks
}
</script>

Random Number Generator
// Returns a random integer from 0 to 9
Math.floor(Math.random() * 10);

Math.random() is used with Math.floor() to return random integers

Scroll to Bottom of a div
(Very Cool)
<script>
let myDiv = document.getElementById("history") ;

// place wheelNum in div and scroll to bottom - - - - -
myDiv.innerHTML += wheelNum + "<br>" ;
myDiv.scrollTop = myDiv.scrollHeight ;
</script>

CSS Overflow Options for a <div>
overflow: scroll;     // always show scrollbars
overflow: hidden;// never show scrollbars nor allow scrolling
Toggle On/Off & Function Timer
Toggle Button - to repeat a Function at an Interval
iD = setInterval(functionName,milliseconds);
iD = clearInterval(iD);
This code requires TWO functions...

#1 A toggle function
    ON - Sets the interval for myFunction
  OFF - Clears the same interval
#2 myFunction

<script>
let toGGle = 0;// toGGle is 0 (0ff) or 1 (on)
let interval_ID;// global variable to store a unique interval_ID

function myToggle() {
if (toGGle == 0) { interval_ID = setInterval(myFunction(),1000) ; toGGle = 1; more javascript ; }
else{ clearInterval(interval_ID) ; toGGle = 0; more javascript ; }
}

function myFunction() {
toGGle = 1;
// actual javascript to run repeating at the set Interval ;
}
</script>

<button class="radio" onclick="myToggle()"></button>
Analog Clock
The Clock Face, Gears, and Hands are created using SVG
CSS is used to style and animate the elements
Javascript is written to actually run the Clock
<script>
let SECONDHAND = document.getElementById("sec") ;
let MINUTEHAND = document.getElementById("min") ;
let HOURHAND = document.getElementById("hour") ;

let interval = setInterval(runTheClock, 1000) ;

function runTheClock() {
let d = new Date() ;
secPosition = 6 * d.getSeconds() ;
minPosition = 6 * d.getMinutes();
hrPosition = 30 * (d.getHours()%12) + (d.getMinutes()/2) ; // the clever bit

SECONDHAND.style.transform = "rotate(" + secPosition + "deg)" ;
MINUTEHAND.style.transform = "rotate(" + minPosition + "deg)" ;
HOURHAND.style.transform = "rotate(" + hrPosition + "deg)" ;
}
</script>

Javascript Animations
<script>
let id = setInterval(frame, 5);// ( function , milliseconds )

function frame() {
if (/* test for finished */) {clearInterval(id); }
else {
/* code to change the element style */
}
}
</script>

Cool Extras

Number → String   String → Number

This is very useful for adding a leading zero to a number display.
7 → 07
Strings are indexed starting at index 0

Consider the number: 2468
We want to use the 'tens digit' numeral at index [2], which is 6

<script>
let Num = 2468 ;// our 4 digit number is indexed from 0 → 3
let tensDigitStr = String(Num)[2] ;// converts Num[2] to a string
let m = Number(tensDigitStr) ;// converts the 'tensDigitStr' back to a number
document.getElementById("demo").innerHTML = m ;// use the tens digit number somehow
</script>
Reload Page

<script>
function reLoad() { location.reload(); }
</script>
'Alien' Characters
Change CSS Styles

JavaScript can change the style of an HTML element.

Multiple style assignments are seperated by semicolons '1st coding here' ; '2nd coding here' ;

Code Fragments
document.body.style.backgroundColor = "#008080" ;

document.body.style.backgroundImage = "linear-gradient(45deg, #1d4949, #1d4949, #00cccc, #1d4949, #1d4949)" ;

let myDiv = document.getElementById("someDiv") ;// creates a useful shortcurt for myDiv

let x = myDiv.value ;// retrieves the value displayed in myDiv

onclick="myDiv.style.transform = "rotate( numBer + "deg" ) " ; "// rotates myDiv

onclick="myDiv.style.transform = "scale( 2.0,2.0) " ; "// scales myDiv

onclick="myDiv.style.color = '#00ffff' ;"// changes the color of text in myDiv - use single quotes inside double

onclick="myDiv.style.font = '30px times' ; "// changes the font in myDiv - use single quotes inside double

<button type="button" class="entry" onclick="functionName()" >Button Text</button>// activates the function

<button type="button" class="clear" onclick='document.getElementById("myDiv").innerHTML = "" '>Clear</button>

document.getElementById("myDiv").innerHTML = x + "px" ;// concatenates the individual values

let name = prompt("Please enter your first name:", "default value" ) ;// OK assigns name = default value

let answer = confirm("Proceed with deposit?") ;// returns true or false

let oN = 0;let interval_ID ;
function myToggle() {
if (oN == 0) { interval_ID = setInterval(functionToRun(),1000) ; oN = 1; }// (function, milliseconds)
else { clearInterval(interval_ID) ; oN = 0 ; }// clears interval stopping functionToRun
}

function functionName() {
// block of code to be executed
}