JavaScript can change the source of an HTML <img>
.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; }
HTML Buttons can execute javascript functions:
<button type="button" onclick="functionName()" >Button Text</button>
( ) | Round Brackets (parenthesis) process variables |
[ ] | Square Brackets are used for arrays |
{ } | Curly Brackets (braces) contain javascript code |
let a = 5; let b = 6.33; let c = a + b;
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' |
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)
Function code example...<script>
function functionName() {
// block of code to be executed
}
</script>
A function can be called called using...<script>
function myRoulette() {
wheelNum = Math.floor(Math.random() * 38);
if (wheelNum > 36) {wheelNum = "00";}
document.getElementById("wHeel").innerHTML = wheelNum ;
}
</script>
onClick<button type="button" onclick="myRoulette()" >Run Function</button>onmouseover<div onmouseover="myRoulette()" >div element</div>
myDiv.innerHTML = "" ; // clears the div
myDiv.innerHTML = "$ " + x ;
The box below is a <div> styled by a CSS class named .outputbox and assigned an id.
✓ Use single quotes for the CSS style = 'definitions'.
<script>
ans1 = "<span class = 'red'>" + "The answer is " + "</span>" ;
ans2 = "√" + "<span style = 'text-decoration: overline;'>" + " 2 " + "</span>" + " = 1.414" ;
OR
ans1 = "<span class = 'red'>The answer is </span>" ; // shorter version
Fot the .innerHTML output, use the variables:
myDiv.innerHTML = ans1 + ans2 ;
ans2 = "√<span style = 'text-decoration: overline;'> 2 </span> = 1.414" ; // shorter version
</script>
<button type="button" class="entry" onclick="print()">Print this page</button>
The Alert() Method may be called alone OR within a function
Internal text formatting can be tricky
Also they can be annoying — use sparingly
<button type="button" class="entry" onclick="myAlert()">Alert Box</button>
else if(isNaN(y)) {
else { All remaining javaScript code . . . }
alert("NOT a number! Try again." ) ;
document.getElementById("answerBox").innerHTML = """ + x + "" is NOT a number. Input MUST be a number." ; }
</script>
<script>
function textboxFunction() {
let x = document.getElementById("textBox").value; // retrieves the value displayed
document.getElementById("textOut").innerHTML = x;
}
</script>
<script>
function numberFunction() {
let x = document.getElementById("numBox").value; // retrieves the value displayed
document.getElementById("numOut").innerHTML = x;
}
</script>
else if and else are optional
== | 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 |
<script>
const arr = [ "Tesla",1,3,5,7,9 ] ;
</script>
<script>
const arr = [ "Tesla" ,2,4,6,8 ] ;
let x = arr[0] ; // returns x = Tesla
let y = arr[1] ; // returns y = 2
</script>
<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>
<script>
const arr = [ "Tesla" ,1,3,5,7,9 ] ;
let termx = arr[ 0 ];
// do something using Tesla
</script>
const fruits = ["Banana", "Orange", "Apple", "Mango"] ;</script>
fruits.push("Kiwi"); document.getElementById("idName").innerHTML = fruits;
fruits.pop("Apple"); document.getElementById("idName").innerHTML = fruits;
Result...
fruits = ["Banana", "Orange", "Mango", "Kiwi"] ; // "Kiwi" added with push(), "Apple" removed with pop()
const fruits = ["Banana", "Orange", "Apple", "Mango", 2, 3, 1] ;</script>
fruits.sort(); document.getElementById("idName").innerHTML = fruits;
fruits.reverse(); document.getElementById("idName").innerHTML = fruits;
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
<script>
const points = [40, 100, 1, 5, 25, 10] ;</script>
points.sort( function(a, b) {return a - b} ); document.getElementById("idName").innerHTML = points;
points.reverse() ); document.getElementById("idName").innerHTML = points;
Results...
1) points = [1, 5, 10, 25, 40, 100] ; // first sorts ascending
2) points = [100, 40, 25, 10, 5, 1] ; // then sorts descending
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>
Egyptian Hieroglyphics Unicode Travel & Places
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.PI | pi π | returns 3.141592653589793... |
Math.PI.toFixed(5) | pi to 5 decimal places | returns 3.14159 |
Math.E | Euler's number e | returns 2.718281828459045... |
Math.E.toFixed(5) | e to 5 decimal places | returns 2.71828 |
Φ = ( 1 + √5 ) ⁄ 2 | Φ Golden Ratio | returns 1.618033988749895... |
1 ⁄ Φ | Inverse Golden Ratio | returns 0.618033988749895... |
Math.SQRT2 | √2 | returns 1.4142135623730951... |
Math.SQRT1_2 | √2 ⁄ 2 | returns 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 false | useful in if () { } statements |
** | Exponentiation | y = x ** 2 | x² |
** | Exponentiation (square root) | y = x ** .5 | √x |
** | Exponentiation (more roots) | y = x ** (1/3) | 3√x cube root of x |
++ | Increment | x = x++ | adds 1 to x |
-- | Decrement | x = x-- | subtracts 1 from x |
+= | Concatenate1 | x += y | concatenates y to x useful for strings in loops |
% | Modulus (division remainder) | x = 5 % 2 | returns 1 (5 ÷ 2 = 2 with remainder of 1) |
1 Concatenate - link together in a series, append to, from the Latin: concatenat
x = -b ± √b² - 4ac
2a
where a ≠ 0
function startTime() {
function getTimer() {
function stopTimer() { // clears the intervalID, therefore stops calling the "getTimer" function
function typeWriter() {
Math.random() is used with Math.floor() to return random integers
// place wheelNum in div and scroll to bottom - - - - -
#1 A toggle function
function myToggle() {
function myFunction() {
let interval = setInterval(runTheClock, 1000) ;
function runTheClock() {
SECONDHAND.style.transform = "rotate(" + secPosition + "deg)" ;
function frame() {
Consider the number:
𝒾 = √ -1
</canvas>Correct Order of <script> Sequencing...
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>
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>
direction is optional, false is default (clockwise), true is counter clockwise
Complete circle: 0 → 2*Math.PI
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>
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>
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>
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>
function clearField() {
const context = myCanvas.getContext('2d') ;
context.clearRect(0, 0, 960, 500) ;
}
</script>
const d = new Date() ;
document .getElementById("dateBox").innerHTML = d ;
// default format
</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>
let intervalID; // global variable to store the unique intervalID
intervalID = setInterval(getTimer,1000) ; // begins the intervals for calling "getTimer" function
}
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 ;
}
clearInterval(intervalID) ;
document.getElementById("timeBox").innerHTML = "";
}
</script>
let i = 0 ;
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>
Math.floor(Math.random() * 10);
(Very Cool)
let myDiv = document.getElementById("history") ;
myDiv.innerHTML += wheelNum + "<br>" ;
myDiv.scrollTop = myDiv.scrollHeight
</script>
overflow: hidden; // never show scrollbars nor allow scrolling
iD = setInterval(functionName,milliseconds);
iD = clearInterval(iD);
ON - Sets the interval for myFunction
OFF - Clears the same interval
#2 myFunction
let toGGle = 0; // toGGle is 0 (0ff) or 1 (on)
let interval_ID; // global variable to store a unique interval_ID
if (toGGle == 0) { interval_ID = setInterval(myFunction(),1000) ; toGGle = 1; more javascript ; }
else{ clearInterval(interval_ID) ; toGGle = 0; more javascript ; }
}
toGGle = 1;
// actual javascript to run repeating at the set Interval ;
}
</script>
CSS is used to style and animate the elements
Javascript is written to actually run the Clock
let SECONDHAND = document.getElementById("sec") ;
let MINUTEHAND = document.getElementById("min") ;
let HOURHAND = document.getElementById("hour") ;
let d = new Date() ;
secPosition = 6 * d.getSeconds() ;
minPosition = 6 * d.getMinutes();
hrPosition = 30 * (d.getHours()%12) + (d.getMinutes()/2) ; // the clever bit
MINUTEHAND.style.transform = "rotate(" + minPosition + "deg)" ;
HOURHAND.style.transform = "rotate(" + hrPosition + "deg)" ;
}
</script>
1 - Create an Animation Container
2 - Style the Elements
let id = setInterval(frame, 5); // ( function , milliseconds )
if (/* test for finished */) {clearInterval(id); }
else {
/* code to change the element style */
}
}
</script>
7 → 07
Strings are indexed starting at index 0
We want to use the 'tens digit' numeral at index [2], which is 6
JavaScript can change the style of an HTML element.
Multiple style assignments are seperated by semicolons '1st coding here' ; '2nd coding here' ;
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 functionName() {
function myToggle() {
if (oN == 0) { interval_ID = setInterval(functionToRun(),1000) ; oN = 1; } // (function, milliseconds)
else { clearInterval(interval_ID) ; oN = 0 ; } // clears interval stopping functionToRun
}
// block of code to be executed
}