JavaScript Code Volume 1 by Christopher Topalian - 2nd Edition
JavaScript Code Volume 1 by Christopher Topalian - 2nd Edition
javascript: alert("Hi");
Hi
OK
return name;
}
}());
/*
Select All of the Code and
press Ctrl + C to Copy it.
Open Web Browser Console with F12
Enter Name
Hi Chris Topalian
Chris Topalian
OK Cancel OK
Shortcut is Control + D
We should now have a Bookmark created.
Edit Our Bookmark to Add Our JS
Right Click on
the Bookmark
we made
Properties
Left Click on
Properties
URL
javascript: alert("Hi");
ourBookmarklet
Hi
OK
return name;
}
if (name == "john")
{
alert("Hi " + name);
}
}
askName();
}());
/* John or JOHN or jOhN will activate */
/* Jo hn or JOH N or J O H N will NOT activate */
/* if diagram */
start
test
FALSE
TRUE
body
Exit
/* if diagram with a test condition */
if
FALSE
name == "john"
TRUE
Exit
javascript:(
/* prompt, if else, toLowerCase, == Equal To */
function()
{
function askName()
{
let name = prompt("Enter
Name").toLowerCase();
if (name == "john")
{
return "Hi John";
}
else
{
return "Hi " + name + ". Where is John?";
}
}
alert(askName());
}());
javascript:(
/* prompt, if else, toLowerCase != Not Equal To */
function()
{
function askName()
{
let name = prompt("Enter
Name").toLowerCase();
if (name != "john")
{
return "Hi " + name + ". Where is John?";
}
else
{
return "Hi John";
}
}
alert(askName());
}());
javascript:(
/* prompt OK and Cancel Button Responses */
function()
{
function askName()
{
let name = prompt("Enter Name");
if (name == null)
{
return "You pressed the Cancel button";
}
if (name == "")
{
return "You pressed OK without first
entering your name";
}
return name;
}
alert("Hi " + askName());
}());
/*
if the person enters their name and presses OK,
it says their name.
if the person presses the OK button without first
entering their name, it tells them that they didn’t
enter their name.
if the person presses the Cancel button it tells
them that they pressed the Cancel button.
*/
javascript:(
/* prompt if else if, < less than, > greater than */
function()
{
function askQuestion()
{
let question = prompt("What is 5 x 5?");
alert(askQuestion());
}());
javascript:(
/* prompt, if else if, do while loop, <, >, != */
function()
{
function askQuestion()
{
let message;
do
{
let question = prompt("What is 5 x 5?");
askQuestion();
}());
/* do while loop diagram */
start
body
FALSE
Exit test
TRUE
javascript:(
/* prompt, if, while loop, < less than */
function()
{
function askQuestion()
{
let players = prompt("Enter Number of
Players");
let x = 0;
start
FALSE
Exit test
TRUE
body
javascript:(
/* prompt, while loop, <= less than equal to */
function()
{
function askQuestion()
{
let players = prompt("Enter Number of
Players");
let x = 1;
x++;
}
}
askQuestion();
}());
javascript:(
/* prompt, for loop, createElement */
function()
{
function askQuestion()
{
let players = prompt("Enter Number of
Players");
let mainDiv =
document.createElement("div");
mainDiv.style.position = "absolute";
mainDiv.style.width = 200 + "px";
mainDiv.style.height = 200 + "px";
mainDiv.style.display = "flex";
mainDiv.style.flexDirection = "column";
mainDiv.style.overflowY = "scroll";
document.body.append(mainDiv);
for (let x = 0; x < players; x++)
{
let player =
document.createElement("button");
player.onclick = function()
{
alert("Player " + x);
};
mainDiv.append(player);
}
}
askQuestion();
}());
/* for loop diagram */
Start number
FALSE
Exit test
TRUE
body
increment++
javascript:(
/* prompt, for loop with break */
function()
{
function askQuestion()
{
let players = prompt("Enter Number of
Players");
break;
}
console.log("Player " + x + ", ");
}
}
askQuestion();
}());
/*
we use a for loop to display how many players
the user chose and use break if it is not enough
players chosen
*/
javascript:(
/* Date, Time, Time zone */
function()
{
function getDateAndTime()
{
let currentDate = new Date();
return currentDate;
}
console.log(getDateAndTime());
alert(getDateAndTime());
}());
let dateString =
currentDate.toLocaleString();
return dateString;
}
console.log(getDateAndTime());
alert(getDateAndTime());
}());
/* 8/27/2023, 7:35:23 AM */
javascript:(
/* Date - Year */
function()
{
function getTheYear()
{
let currentDate = new Date();
return year;
}
}());
/* Year: 2023 */
javascript:(
/* Date - Month */
function()
{
function getTheMonth()
{
let currentDate = new Date();
if (month == 0)
{
return "January";
}
else if (month == 1)
{
return "February";
}
else if (month == 2)
{
return "March";
}
else if (month == 3)
{
return "April";
}
else if (month == 4)
{
return "May";
}
else if (month == 5)
{
return "June";
}
else if (month == 6)
{
return "July";
}
else if (month == 7)
{
return "August";
}
else if (month == 8)
{
return "September";
}
else if (month == 9)
{
return "October";
}
else if (month == 10)
{
return "November";
}
else if (month == 11)
{
return "December";
}
return month;
}
}());
/*
August
*/
javascript:(
/* Date - Day */
function()
{
function getTheDay()
{
let currentDate = new Date();
if (day == 0)
{
return "Sunday";
}
else if (day == 1)
{
return "Monday";
}
else if (day == 2)
{
return "Tuesday";
}
else if (day == 3)
{
return "Wednesday";
}
else if (day == 4)
{
return "Thursday";
}
else if (day == 5)
{
return "Friday";
}
else if (day == 6)
{
return "Saturday";
}
return day;
}
}());
/*
Sunday
*/
javascript:(
/* Date - Time - Military - 24 Hour Format */
function()
{
function getMilitaryTime()
{
let currentDate = new Date();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
return timeString;
}
}());
/*
Time: 17:17:28
*/
javascript:(
/* Date - Time - AM or PM - 12 Hour Format */
function()
{
function getTheTime()
{
let currentDate = new Date();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let amOrPm;
return timeString;
}
}());
/* Time: 8:50:17 AM */
javascript:(
/* Date - Time - AM or PM - 12 Hour Format –
Updates Time in a div */
function()
{
function getTheTime()
{
let currentDate = new Date();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let amOrPm;
return timeString;
}
function createTimeText()
{
let timeDiv =
document.createElement("div");
timeDiv.style.position = "fixed";
timeDiv.style.right = "0px";
timeDiv.style.top = "0px";
timeDiv.style.paddingLeft = "15px";
timeDiv.style.paddingRight = "15px";
timeDiv.style.paddingTop = "5px";
timeDiv.style.paddingBottom = "5px";
timeDiv.style.borderRadius = "8px";
timeDiv.style.backgroundColor = "rgb(0, 0,
0)";
timeDiv.style.fontSize = "30px";
timeDiv.style.color = "rgb(255, 255, 255)";
setInterval(function()
{
timeDiv.innerHTML = getTheTime();
}, 1000);
document.body.append(timeDiv);
}
createTimeText();
}());
/* Time: 8:57:17 AM */
javascript:(
/* Date - Time - Time Zones America */
function()
{
function getCurrentTimeAndDate(timezone,
label)
{
const now = new Date();
const options = {
timeZone: timezone,
timeStyle: 'short',
dateStyle: 'medium'
};
const formattedTimeAndDate =
now.toLocaleString(undefined, options);
console.log(getCurrentTimeAndDate('America/D
enver', 'Mountain'));
console.log(getCurrentTimeAndDate('America/C
hicago', 'Central'));
console.log(getCurrentTimeAndDate('America/
New_York', 'East Coast'));
}());
function openWebpage()
{
window.location.href = url001;
}
openWebpage();
}());
javascript:(
/* URL of the webpage */
function()
{
function urlOfPage()
{
let url = window.location.href;
return url;
}
console.log(urlOfPage());
alert(urlOfPage());
}());
javascript:(
/* Title of the webpage */
function()
{
function titleOfPage()
{
let title = document.title;
return title;
}
console.log(titleOfPage());
alert(titleOfPage());
}());
javascript:(
/* Title and URL of the webpage */
function()
{
function titleOfPage()
{
let title = document.title;
return title;
}
function urlOfPage()
{
let url = window.location.href;
return url;
}
console.log(titleOfPage() + "\n" + urlOfPage());
let pageData =
"Title: " + pageTitle + "\n" +
"URL: " + pageURL;
return pageData;
}
console.log(getPageData());
alert(getPageData());
}());
javascript:(
/* Elements - How Many Elements on a Page */
function()
{
function howManyElements()
{
let elements =
document.getElementsByTagName("*");
return elementCount;
}
console.log(howManyElements());
alert(howManyElements());
}());
javascript:(
/* Images - How many Images on a page */
function()
{
function howManyImages()
{
let images =
document.getElementsByTagName('img');
return imageCount;
}
return linksCount;
}
}());
javascript:(
/* How many specified elements */
function()
{
function
howManySpecifiedElements(whichElementType)
{
let elements =
document.getElementsByTagName(whichEleme
ntType);
return elementCount;
}
console.log(howManySpecifiedElements("a"));
alert(howManySpecifiedElements("a"));
}());
javascript:(
/* Style Links */
function()
{
function styleLinks()
{
let links =
document.getElementsByTagName('a');
styleLinks();
}());
javascript:(
/* Style Specified Elements */
function()
{
function
styleSpecifiedElements(whichElementType)
{
let elements =
document.getElementsByTagName(whichEleme
ntType);
document.head.append(ourStyle);
}
textColorChange();
}());
document.head.append(ourStyle);
}
textColorChange("aqua");
}());
javascript:(
/* Style All Elements of a Specified Type */
function()
{
function styleElement(whichElementType)
{
let elements =
document.getElementsByTagName(whichEleme
ntType);
elements[x].style.borderWidth = 1 + "px";
elements[x].style.borderRadius = 8 +
"px";
elements[x].style.borderColor = "rgb(0,
255, 255)";
elements[x].style.fontSize = 20 + "px";
elements[x].style.fontWeight = "bold";
}
}
styleElement("div");
}());
javascript:(
/* Number of Elements of Specified Type on
Page */
function()
{
function
getNumberOfSpecifiedElement(whichElement)
{
let elements =
document.getElementsByTagName(whichEleme
nt);
return elements.length;
}
console.log(getNumberOfSpecifiedElement("div
"));
alert(getNumberOfSpecifiedElement("div"));
}());
javascript:(
/* Show the innerHTML of each specified
element type on a Page */
function()
{
function
showElementInnerHTML(whichElementType)
{
let report = "";
let elements =
document.getElementsByTagName(whichEleme
ntType);
report += "\n";
}
console.log(report);
alert(report);
}
showElementInnerHTML("p");
}());
/*
Show innerHTML of element types, such as:
/*
<p>: Paragraph elements.
<h1>, <h2>, <h3>, <h4>, <h5>, <h6>: Headings of
different levels.
<div>: Div elements.
<span>: Span elements.
<li>: List item elements within <ul> or <ol>.
<a>: Anchor links.
<button>: Buttons.
<label>: Labels for form elements.
<textarea>: Textareas within forms.
<option>: Options within <select> elements.
<blockquote>: Block quotes.
<cite>: Citations within block quotes.
<abbr>: Abbreviations.
<code>: Code snippets.
<pre>: Preformatted text.
*/
javascript:(
/* Show the src of each specified element type
on a Page */
function()
{
function
showElementsSrc(whichElementType)
{
let report = "";
let elements =
document.getElementsByTagName(whichEleme
ntType);
report += "\n";
}
console.log(report);
alert(report);
}
showElementsSrc("img");
}());
/*
Show src of element types, such as:
<img>: Image elements.
<input>: Input elements.
<script>: Script elements.
*/
javascript:(
/* Show the href of each specified element type
on a Page */
function()
{
function
showElementsHref(whichElementType)
{
let report = "";
let elements =
document.getElementsByTagName(whichEleme
ntType);
report += "\n";
}
console.log(report);
alert(report);
}
showElementsHref("link");
}());
/*
Show href of element types, such as:
let elements =
document.getElementsByTagName(whichEleme
ntType);
elements[x].style.borderStyle = "solid";
elements[x].style.borderWidth = 2 + "px";
elements[x].style.borderColor = "rgb(0,
255, 255)";
elements[x].style.fontWeight = "bold";
report += elements[x].innerHTML;
report += "\n";
}
console.log(report);
alert(report);
}
showElementInnerHTML("p");
}());
javascript:(
/* Show All Image URLS */
function()
{
function showImageUrls()
{
let report = "";
let theLinks =
document.getElementsByTagName("img");
report += "\n";
}
console.log(report);
alert(report);
}
showImageUrls();
}());
/*
alert shows a limited amount of characters.
let images =
document.getElementsByTagName("img");
images[x].style.borderWidth = 2 + "px";
report += "\n";
}
console.log(report);
alert(report);
}
showImageUrls();
}());
javascript:(
/* Show All Buttons with style */
function()
{
function showButons()
{
let report = "";
let buttons =
document.getElementsByTagName("button");
buttons[x].style.borderWidth = 2 + "px";
buttons[x].style.borderColor = "rgb(0,
255, 255)";
report += buttons[x].innerHTML;
report += "\n";
}
console.log(report);
alert(report);
}
showButons();
}());
javascript:(
/* Show All Links with style */
function()
{
function showLinks()
{
let report = "";
let links =
document.getElementsByTagName("a");
links[x].style.borderWidth = 2 + "px";
report += "\n";
}
console.log(report);
alert(report);
}
showLinks();
}());
javascript:(
/* Get Selected Text */
function()
{
function getSelectedText()
{
let selectedText =
window.getSelection().toString();
return selectedText;
}
console.log(getSelectedText());
alert(getSelectedText());
}());
javascript:(
/* Replace Words on a Webpage */
function()
{
function replaceWords()
{
let elements =
document.getElementsByTagName('*');
theElement.innerHTML =
theElement.innerHTML.replace(/\b(?:News)\b/gi,
'Howdy');
theElement.innerHTML =
theElement.innerHTML.replace(/\b(?:The|Was|A|
To|Were)\b/gi, 'LOL');
theElement.innerHTML =
theElement.innerHTML.replace(/\b(?:What|
Where|When|Why|How)\b/gi, 'Funny');
}
}
replaceWords();
}());
/*
let elements =
document.getElementsByTagName('*');
}());
javascript:(
/* Images Display to None */
function()
{
function hideImages()
{
let images =
document.getElementsByTagName('img');
hideImages();
}());
javascript:(
/* Images - Gray Scale */
function()
{
function makeImagesGrayScale()
{
let theImages =
document.getElementsByTagName('img');
makeImagesGrayScale();
}());
javascript:(
/* Toggle Images On/Off */
function()
{
function toggleImagesOnOrOff()
{
let images =
document.getElementsByTagName('img');
toggleImagesOnOrOff();
}());
/*
if images are hidden, it will show them
mouseTriggersStyle();
}());
javascript:(
/* First Click Does X, Second Click Does Y */
function()
{
function mouseTriggersStyle()
{
let toggleFlag = false;
document.onclick = function()
{
let elements =
document.getElementsByTagName('*');
toggleFlag = !toggleFlag;
};
}
mouseTriggersStyle();
}());
/*
The next tutorial shows a variation of this idea.
Choose the way that you find to be more natural.
*/
javascript:(
/* First Click Does X, Second Click Does Y -
Variation */
function()
{
let toggleFlag = false;
function mouseTriggersStyle()
{
document.onclick = function()
{
let elements =
document.getElementsByTagName('*');
toggleFlag = false;
}
}
};
}
mouseTriggersStyle();
}());
javascript:(
/* First Click do X, Second Click do Y, Third Click
do Z */
function()
{
let state = 0;
function toggleFontWeightAndColor(element)
{
if (state === 0)
{
element.style.fontWeight = "normal";
element.style.color = "red";
state = 1;
}
element.style.color = "green";
state = 2;
}
else
{
element.style.color = "blue";
state = 0;
}
}
function mouseTriggersStyle()
{
document.onclick = function()
{
let elements =
document.getElementsByTagName('*');
mouseTriggersStyle();
}());
javascript:(
/* Random Number Generator from 1 to 100 */
function()
{
function generateRandomNumber()
{
let randomNumber =
Math.floor(Math.random() * 100) + 1;
return randomNumber;
}
console.log(generateRandomNumber());
alert(generateRandomNumber());
}());
document.body.style.backgroundColor =
randomColor;
}
randomBackgroundColor();
}());
javascript:(
/* Random Background Color - Variation */
function()
{
function randomValue()
{
return Math.floor(Math.random() * 255);
}
document.body.style.backgroundColor =
randomColor;
}());
javascript:(
/* Random Greeting */
function()
{
let greetings =
[
"Hi",
"Howdy.",
"How ya doing?",
"You having fun?",
"Glad you are here.",
"Nice weather today.",
"It's such a nice day out."
];
function makeRandomMessage(whichArray)
{
let randomGreeting =
whichArray[Math.floor(Math.random() *
whichArray.length)];
return randomGreeting;
}
let message =
makeRandomMessage(greetings);
console.log(message);
alert(message);
}());
javascript:(
/* Random Quote Generator */
function()
{
function generateRandomQuote()
{
let quotes =
[
"Always be kind",
"Be excellent to each other",
"Live long and prosper"
];
return randomQuote;
}
let quote = generateRandomQuote();
console.log(quote);
alert(quote);
}());
javascript:(
/* Random Font for the entire Webpage */
function()
{
let fonts =
[
'Arial',
'Times New Roman',
'Courier New',
'Garamond',
'Avant Garde',
'Palatino Linotype'
];
function makeRandomFont()
{
let elements =
document.getElementsByTagName('*');
let randomFont =
fonts[Math.floor(Math.random() * fonts.length)];
makeRandomFont();
}());
javascript:(
/* Random Background Color */
function()
{
function getRandomColor()
{
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
document.body.style.backgroundColor =
getRandomColor();
}());
javascript:(
/* Random BG to Specified Element */
function()
{
function
styleSpecifiedElements(whichElementType)
{
let elements =
document.getElementsByTagName(whichEleme
ntType);
elements[x].style.backgroundColor =
randomColor;
}
}
styleSpecifiedElements("a");
}());
javascript:(
/* Random BG to Specified Elements - Variation
*/
function()
{
function
styleSpecifiedElements(whichElementType,
whichRgbColor)
{
let theElements =
document.getElementsByTagName(whichEleme
ntType);
}());
javascript:(
/* Random Positions for a Circle */
function()
{
function createCircle()
{
let circle = document.createElement("div");
circle.id = "circle";
circle.style.position = "absolute";
circle.style.width = "20px";
circle.style.height = "20px";
circle.style.background = "aqua";
circle.style.borderRadius = "50%";
document.body.append(circle);
return circle;
}
function getRandomPosition()
{
let x = Math.floor(Math.random() *
window.innerWidth);
let y = Math.floor(Math.random() *
window.innerHeight);
return {
x: x,
y: y
};
}
function moveObject(circle)
{
let pos = getRandomPosition();
circle.style.left = pos.x + "px";
circle.style.top = pos.y + "px";
}
function moveObjectRandomPositions()
{
let circle = createCircle();
moveObjectRandomPositions();
}());
javascript:(
/* Random Positions and Colors for a Circle */
function()
{
function createCircle()
{
let circle = document.createElement("div");
circle.id = "circle";
circle.style.position = "absolute";
circle.style.width = "20px";
circle.style.height = "20px";
circle.style.borderRadius = "50%";
document.body.append(circle);
return circle;
}
function getRandomPosition()
{
let x = Math.floor(Math.random() *
window.innerWidth);
let y = Math.floor(Math.random() *
window.innerHeight);
return {
x: x,
y: y
};
}
function getRandomColor()
{
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb("+r+", "+g+", "+b+")";
}
function moveObject(circle)
{
let pos = getRandomPosition();
circle.style.backgroundColor =
getRandomColor();
function moveObjectRandomPositions()
{
let circle = createCircle();
moveObject(circle);
}());
javascript:(
/* Random Positions and Colors for a Circle -
How Many */
function()
{
function createCircle()
{
let circle = document.createElement("div");
circle.id = "circle";
circle.style.position = "absolute";
circle.style.width = "20px";
circle.style.height = "20px";
circle.style.borderRadius = "50%";
document.body.append(circle);
return circle;
}
function getRandomPosition()
{
let x = Math.floor(Math.random() *
window.innerWidth);
let y = Math.floor(Math.random() *
window.innerHeight);
return {
x: x,
y: y
};
}
function getRandomColor()
{
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb("+r+", "+g+", "+b+")";
}
function moveObject(circle)
{
let pos = getRandomPosition();
circle.style.backgroundColor =
getRandomColor();
function
moveObjectRandomPositions(numberOfCircles)
{
for (let i = 0; i < numberOfCircles; i++)
{
let circle = createCircle();
moveObject(circle);
}
/* move every 1 second */
setInterval(function()
{
let circles =
document.querySelectorAll("#circle");
if (numberOfCircles && !
isNaN(numberOfCircles))
{
moveObjectRandomPositions(Number(numberO
fCircles));
}
else
{
alert("Enter 1 or higher");
}
}());
javascript:(
/* Random Pos, Size, Color for Circles */
function()
{
function createCircle()
{
let circle = document.createElement("div");
circle.id = "circle";
circle.style.position = "absolute";
let size = getRandomSize();
circle.style.width = size + "px";
circle.style.height = size + "px";
circle.style.borderRadius = "50%";
document.body.append(circle);
return circle;
}
function getRandomSize()
{
// random size between 10 and 100 pixels
return Math.floor(Math.random() * 91) + 10;
}
function getRandomPosition()
{
let x = Math.floor(Math.random() *
window.innerWidth);
let y = Math.floor(Math.random() *
window.innerHeight);
return {
x: x,
y: y
};
}
function getRandomColor()
{
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return "rgb("+r+", "+g+", "+b+")";
}
function moveObject(circle)
{
let pos = getRandomPosition();
circle.style.backgroundColor =
getRandomColor();
function
moveObjectRandomPositions(numberOfCircles)
{
for (let i = 0; i < numberOfCircles; i++)
{
let circle = createCircle();
moveObject(circle);
}
}());
javascript:(
/* Random Border Color with Timer */
function()
{
let theTimer;
let isRunning = false;
function getRandomColor()
{
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
return 'rgb('+r+', '+g+', '+b+')';
}
function toggleColorChange()
{
if (!isRunning)
{
document.body.style.borderStyle =
"solid";
document.body.style.borderColor =
"rgb(255, 255, 255)";
theTimer = setInterval(function()
{
document.body.style.borderColor =
getRandomColor();
}, 1000);
}
else
{
clearInterval(theTimer);
document.body.style.backgroundColor =
'';
}
isRunning = !isRunning;
}
toggleColorChange();
document.body.addEventListener('click',
toggleColorChange);
}());
javascript:(
/* Replace Images with a Random Image from
our Array */
function()
{
const textures =
[
'https://collegeofscripting.weebly.com/uploads/
6/4/4/8/64482293/wood1.jpg',
'https://collegeofscripting.weebly.com/uploads/
6/4/4/8/64482293/copper.jpg',
'https://collegeofscripting.weebly.com/uploads/
6/4/4/8/64482293/silver.jpg',
'https://collegeofscripting.weebly.com/uploads/
6/4/4/8/64482293/gold.jpg',
];
function replaceImages()
{
const images =
document.getElementsByTagName('img');
images[x].src = textures[imageIndex];
replaceImages();
}());
/* replaces all images on the current page with
random images from our array */
javascript:(
/* Replace Images with specified Image */
function()
{
function replaceImages()
{
let images =
document.getElementsByTagName('img');
images[x].alt = 'Asphalt';
}
}
replaceImages();
}());
javascript:(
/* Video Pause - Pauses the Video */
function()
{
function videoPause()
{
let theVideo =
document.querySelector('video');
theVideo.pause();
}
videoPause();
}());
theVideo.play();
}
videoPlay();
}());
javascript:(
/* Video Back 2 Seconds */
function()
{
function videoSkipBackwards()
{
let theTime =
document.querySelector('video').currentTime +=
-2;
}
videoSkipBackwards();
}());
javascript:(
/* Video Forward 2 Seconds */
function()
{
function videoSkipForward()
{
let theTime =
document.querySelector('video').currentTime +=
2;
}
videoSkipForward();
}());
javascript:(
/* Video Forward 2 Seconds, Keep Activating */
function()
{
function videoSkipForward()
{
document.querySelector('video').currentTime
+= 2;
}
setInterval(videoSkipForward, 1000);
}());
javascript:(
/* Video currentTime */
function()
{
function videoCurrentTime()
{
let time =
document.querySelector('video').currentTime;
return time;
}
console.log(videoCurrentTime());
alert(videoCurrentTime());
}());
javascript:(
/* Video currentTime with round */
function()
{
function videoCurrentTime()
{
let time =
document.querySelector('video').currentTime;
return roundedTime;
}
console.log(videoCurrentTime());
alert(videoCurrentTime());
}());
javascript:(
/* Video currentTime using toFixed */
function()
{
function videoCurrentTime()
{
let time =
document.querySelector('video').currentTime;
return formattedTime;
}
console.log(videoCurrentTime());
alert(videoCurrentTime());
}());
javascript:(
/* Video - Set the currentTime */
function()
{
function videoSetTime(whichSeconds)
{
document.querySelector('video').currentTime
= whichSeconds;
}
videoSetTime(60);
}());
javascript:(
/* Video - Duration - Total Length in Seconds */
function()
{
function videoGetDuration()
{
let theDuration =
document.querySelector('video').duration;
return theDuration;
}
console.log(videoGetDuration());
alert(videoGetDuration());
}());
javascript:(
/* Video - loop if true, non loop if false */
function()
{
function videoLoop(whichLoopSetting)
{
document.querySelector('video').loop =
whichLoopSetting;
}
videoLoop(true);
}());
javascript:(
/* Video muted if true, unmuted if false */
function()
{
function videoMute(whichMuteSetting)
{
document.querySelector('video').muted =
whichMuteSetting;
}
videoMute(true);
}());
javascript:(
/* Video URL - window.location.href */
function()
{
function videoSource()
{
let theSrc = window.location.href;
return theSrc;
}
alert(videoSource());
}());
javascript:(
/* Video Volume - 0.0 Mute, 1.0 Full */
function()
{
function videoVolume(whichVolume)
{
document.querySelector('video').volume =
whichVolume;
}
videoVolume(0.5);
}());
javascript:(
/* Video Volume - Get Volume Level 0.0 to 1.0 */
function()
{
function videoVolumeGet()
{
let theSrc =
document.querySelector('video').volume;
return theSrc;
}
alert(videoVolumeGet());
}());
javascript:(
/* Video Speed to Custom Value */
/* Set the speed value of the video, such as: 0.0,
0.25, 0.5, 0.75, 1.00, 1.25, 1.5, 1.75, 2.00, 20.0, or
super slow 0.01 */
function()
{
function videoSpeedSet(whichSpeed)
{
document.querySelector('video').playbackRate
= whichSpeed;
}
videoSpeedSet(0.5);
}());
javascript:(
/* Video - Custom Speed */
function()
{
function videoSpeedSet()
{
const speedInput = prompt('Enter a Speed',
'0.50');
const videoSpeed =
parseFloat(speedInput);
document.querySelector('video').playbackRate
= videoSpeed;
}
videoSpeedSet();
}());
javascript:(
/* YouTube - Style Description Border color */
function()
{
function createBorderAroundVideoInfo()
{
let theBorder =
document.querySelector(".style-scope ytd-
watch-metadata");
theBorder.style.borderStyle = 'solid';
theBorder.style.borderColor = 'aqua';
}
createBorderAroundVideoInfo();
}());
javascript:(
/* YouTube - Get URL, Title, Description, Date */
function()
{
function getInfo()
{
let nameList =
document.querySelectorAll(".style-scope ytd-
video-primary-info-renderer");
theNames += "\n";
}
let theTextArea =
document.createElement("textarea");
theTextArea.style.position = "absolute";
theTextArea.style.left = 100 + 'px';
theTextArea.style.top = 200 + 'px';
theTextArea.style.width = 700 + 'px';
theTextArea.style.height = 200 + 'px';
theTextArea.style.zIndex = "1000";
theTextArea.style.border = "solid 2px
rgba(0,0,100,1.0)";
theTextArea.style.background = "white";
theTextArea.style.fontFamily = "arial";
theTextArea.style.fontWeight = "normal";
theTextArea.style.fontSize = "medium";
theTextArea.style.color = "black";
theTextArea.style.textAlign = "center";
theTextArea.setAttribute("readonly",
"true");
theTextArea.value = theNames;
document.body.append(theTextArea);
}
getInfo();
}());
javascript:(
/* Shows Mouse Position when person clicks the
screen */
function()
{
function mousePos()
{
let mouseX = event.pageX;
let mouseY = event.pageY;
let mousePos =
"Mouse" + "\n" +
"X " + mouseX + "\n" +
"Y " + mouseY;
console.log(mousePos);
document.title = mousePos;
}
window.addEventListener("click", mousePos,
false);
mousePos();
}());
javascript:(
/* Create Video Game Player on Any Webpage */
function()
{
function createPlayer()
{
let player = document.createElement("div");
player.id = "thePlayer";
player.style.position = "absolute";
player.style.left = 0;
player.style.top = 0;
player.style.width = "50px";
player.style.height = "50px";
player.style.zIndex = "15";
player.style.fontFamily = "exo";
player.style.fontSize = "20px";
player.style.fontWeight = "bold";
player.style.color = "rgb(255, 255, 255)";
player.style.textAlign = "center";
player.style.background = "rgba(76, 175,
180, 0.5)";
document.body.append(player);
/*----*/
/*----*/
/*----*/
keyboard[theKeyCode] = e.type ==
'keydown';
};
/*----*/
ourPlayer.y += (theY || 0) *
ourPlayer.speedMultiplier;
ourPlayer.playerId.style.left = ourPlayer.x +
'px';
ourPlayer.playerId.style.top = ourPlayer.y +
'px';
};
/*----*/
/* player controls */
let sensePlayerMotion = function()
{
if (keyboard[keyboard.LEFT])
{
movePlayer(-1, 0);
}
if (keyboard[keyboard.RIGHT])
{
movePlayer(1, 0);
}
if (keyboard[keyboard.UP])
{
movePlayer(0, -1);
}
if (keyboard[keyboard.DOWN])
{
movePlayer(0, 1);
}
};
/*----*/
/*----*/
function scrollIt()
{
document.getElementById("thePlayer").scrollInt
oView(
{
block: "center",
inline: "center"
});
}
let loop001;
function gameLoop()
{
sensePlayerMotion();
scrollIt();
loop001 =
requestAnimationFrame(gameLoop);
}
gameLoop();
}
createPlayer();
}());
javascript:(
/* createElement, append, Make a div, style */
function()
{
function createInfoDiv()
{
let ourDiv = document.createElement("div");
ourDiv.style.position = "absolute";
ourDiv.style.left = "100px";
ourDiv.style.top = "100px";
ourDiv.style.paddingLeft = "10px";
ourDiv.style.paddingRight = "10px";
ourDiv.style.paddingTop = "5px";
ourDiv.style.paddingBottom = "5px";
ourDiv.style.zIndex = "1000";
ourDiv.style.borderStyle = "solid";
ourDiv.style.borderWidth = "1px";
ourDiv.style.borderRadius = "8px";
ourDiv.style.borderColor = "rgb(0, 255,
255)";
ourDiv.style.background = "rgb(0, 0, 0)";
ourDiv.style.fontSize = "30px";
ourDiv.style.fontWeight = "bold";
ourDiv.style.color = "rgb(0, 255, 255)";
ourDiv.style.textAlign = "center";
ourDiv.innerHTML = "Copper";
ourDiv.innerHTML += "<br>";
ourDiv.innerHTML += "29";
document.body.append(ourDiv);
}
createInfoDiv();
}());
javascript:(
/* createElement - id - Right click on the Div and
choose Inspect */
function()
{
function createDiv()
{
let ourDiv = document.createElement("div");
ourDiv.id = "ourDiv";
ourDiv.style.position = "absolute";
ourDiv.style.left = 100 + "px";
ourDiv.style.top = 100 + "px";
ourDiv.style.paddingLeft = "10px";
ourDiv.style.paddingRight = "10px";
ourDiv.style.paddingTop = "5px";
ourDiv.style.paddingBottom = "5px";
ourDiv.style.background = "rgb(0, 0, 0)";
ourDiv.style.borderStyle = "solid";
ourDiv.style.borderWidth = "1px";
ourDiv.style.borderRadius = "8px";
ourDiv.style.borderColor = "rgb(0, 255,
255)";
ourDiv.style.background = "rgb(0, 0, 0)";
ourDiv.style.fontSize = "30px";
ourDiv.style.fontWeight = "bold";
ourDiv.style.color = "rgb(0, 255, 255)";
ourDiv.style.textAlign = "center";
ourDiv.innerHTML = "Right click this div.
Choose Inspect.";
document.body.append(ourDiv);
}
createDiv();
}());
javascript:(
/* createElement, append, Make a Paragraph */
function()
{
function createParagraph()
{
let ourParagraph =
document.createElement("p");
ourParagraph.style.position = "absolute";
ourParagraph.style.top = 100 + 'px';
ourParagraph.style.left = 100 + 'px';
ourParagraph.innerHTML = "Here is the
text.";
document.body.append(ourParagraph);
}
createParagraph();
}());
javascript:(
/* createElement, div, style, url new tab */
function()
{
function createInfoDiv()
{
let copper =
{
name: "copper",
number: "29",
link:
"https://en.wikipedia.org/wiki/Copper"
};
createInfoDiv();
}());
javascript:(
/* createElement, Array Of Objects - link */
function()
{
function createInfoDiv()
{
let myRecord =
[
{
name: "Key",
weight: 140,
link: "https://google.com/news"
},
{
name: "Donald",
weight: 160,
link: "https://google.com"
}
];
let ourDiv = document.createElement("div");
ourDiv.style.position = "absolute";
ourDiv.style.left = "100px";
ourDiv.style.top = "100px";
ourDiv.style.width = "100px";
ourDiv.style.paddingLeft = "10px";
ourDiv.style.paddingRight = "10px";
ourDiv.style.paddingBottom = "15px";
ourDiv.style.paddingTop = "9px";
ourDiv.style.borderRadius = "8px";
ourDiv.style.background = "rgb(0, 0, 0)";
ourDiv.style.zIndex = "1000";
ourDiv.style.fontSize = 30 + "px";
ourDiv.style.color = "rgb(0, 255, 255)";
ourDiv.style.textAlign = "center";
ourDiv.innerHTML = myRecord[0].name;
ourDiv.innerHTML += "<br>";
ourDiv.innerHTML += myRecord[0].weight;
ourDiv.innerHTML += "<br>";
ourDiv.innerHTML += '<a href = \'' +
myRecord[0].link + '\' target = "_blank"> Link
</a>';
document.body.append(ourDiv);
}
createInfoDiv();
}());
/*
We make an Array of Objects that we named
myRecord
The 0 entry of the myRecord array is Key.
output += '<hr>';
ourDiv.innerHTML = output;
createInfoDiv();
}());
/*
Creates a New div on the page with style & url
link of an array of objects, displaying all entries.
We loop through the entries of the myRecords
array to display all of them at once.
The for loop will only continue for as many
entries that are found. In this case, there are
only two entries.
We display all of the entries on a div that we
have made using createElement.
*/
javascript:(
/* createElement, Make a Button */
function()
{
function textMessage(whichText)
{
alert(whichText);
}
function createMessage(whichText)
{
let ourButton =
document.createElement("button");
ourButton.style.position = "absolute";
ourButton.style.left = "100px";
ourButton.style.top = "100px";
ourButton.style.padding = "2px";
ourButton.style.zIndex = "1000";
ourButton.style.background = "rgb(0, 0, 0)";
ourButton.style.fontSize = 22 + "px";
ourButton.style.color = "rgb(255, 255, 255)";
ourButton.innerHTML = "Greeting";
ourButton.onmouseover = function()
{
ourButton.style.color = "rgb(0, 255, 255)";
};
ourButton.onmouseout = function()
{
ourButton.style.color = "rgb(255, 255,
255)";
};
ourButton.onclick = function()
{
textMessage(whichText);
};
document.body.append(ourButton);
createMessage("Hi Everyone");
}());
javascript:(
/* Scene - Position - Get Current Position of the
square object by left clicking it */
function()
{
let horizon = document.createElement('div');
horizon.style.position = 'absolute';
horizon.style.left = '0px';
horizon.style.top = '0px';
horizon.style.width = '100%';
horizon.style.height = '50%';
horizon.style.backgroundColor = 'rgb(0, 100,
200)';
document.body.append(horizon);
/*----*/
/*----*/
/*----*/
let object001 = document.createElement('div');
object001.style.position = 'absolute';
object001.style.left = '400px';
object001.style.top = '500px';
object001.style.width = '20px';
object001.style.height = '20px';
object001.style.backgroundColor = 'tan';
object001.style.cursor = 'pointer';
object001.style.zIndex = '10000';
object001.onclick = function(event)
{
/* get position */
let objectRect =
object001.getBoundingClientRect();
document.body.append(object001);
/*----*/
/*
Result:
X: 400, Y: 500
*/
javascript:(
/* createElement - Get link textContent - right
click removes element */
function()
{
function createInfoDiv()
{
let report = "";
let theLinks =
document.getElementsByTagName("a");
report += "<hr>";
}
ourDiv.oncontextmenu = function()
{
document.getElementById("theDiv").remove();
};
document.body.append(ourDiv);
}
createInfoDiv();
}());
/*
Choose the sytax style that you like using more:
report += "<a href = ' " + theLinks[x] + " ' target =
'_blank'>" + theLinks[x].textContent + "</a>";
*/
javascript:(
/* createElement - Get URL when button is
clicked, onmouseover, onmouseout */
function()
{
function showUrl()
{
let ourButton =
document.createElement("button");
ourButton.style.position = "fixed";
ourButton.style.right = 5 + "px";
ourButton.style.top = 5 + "px";
ourButton.style.borderRadius = 8 + "px";
ourButton.style.paddingLeft = 10 + "px";
ourButton.style.paddingRight = 10 + "px";
ourButton.style.paddingBottom = 5 + "px";
ourButton.style.paddingTop = 5 + "px";
ourButton.style.zIndex = "1000";
ourButton.style.background = "rgb(0, 0, 0)";
ourButton.style.fontSize = 20 + "px";
ourButton.style.fontWeight = "bold";
ourButton.style.color = "rgb(255, 255, 255)";
ourButton.onclick = function()
{
console.log(window.location.href);
alert(window.location.href);
};
ourButton.onmouseover = function()
{
ourButton.style.borderColor = "aqua";
ourButton.style.color = "aqua";
};
ourButton.onmouseout = function()
{
ourButton.style.borderColor = "white";
ourButton.style.color = "white";
};
document.body.append(ourButton);
}
showUrl();
}());
/* onmouseover the button changes style,
onmouseout the button changes style again.
onclick it shows the url of the page in a console
message and alert message box */
javascript:(
/* createElement, Video pause button */
function()
{
function videoPause()
{
let ourButton =
document.createElement("button");
ourButton.id = "theButton";
ourButton.style.position = "absolute";
ourButton.style.left = "100px";
ourButton.style.top = "100px";
ourButton.style.paddingLeft = 10 + "px";
ourButton.style.paddingRight = 10 + "px";
ourButton.style.paddingTop = 5 + "px";
ourButton.style.paddingBottom = 5 + "px";
ourButton.style.borderRadius = 8 + "px";
ourButton.style.zIndex = "1000";
ourButton.style.background = "rgb(0, 0, 0)";
ourButton.style.fontSize = 20 + "px";
ourButton.style.fontWeight = "bold";
ourButton.style.color = "rgb(255, 255, 255)";
ourButton.innerHTML = "Pause Button";
ourButton.onmouseover = function()
{
ourButton.style.color = "rgb(0, 255, 255)";
};
ourButton.onmouseout = function()
{
ourButton.style.color = "rgb(255, 255,
255)";
};
ourButton.onclick = function()
{
let theVideo =
document.querySelectorAll("video");
theVideo.pause();
};
document.body.append(ourButton);
videoPause();
}());
playButton.onmouseover = function()
{
playButton.style.color = "rgb(0, 255, 255)";
};
playButton.onmouseout = function()
{
playButton.style.color = "rgb(255, 255, 255)";
};
playButton.onclick = function()
{
let theVideo =
document.querySelectorAll("video");
theVideo.play();
};
document.body.append(playButton);
/*----*/
let pauseButton =
document.createElement("button");
pauseButton.id = "pauseButton";
pauseButton.style.position = "absolute";
pauseButton.style.left = 100 + "px";
pauseButton.style.top = 150 + "px";
pauseButton.style.paddingLeft = 10 + "px";
pauseButton.style.paddingRight = 10 +
"px";
pauseButton.style.paddingTop = 5 + "px";
pauseButton.style.paddingBottom = 5 +
"px";
pauseButton.style.borderRadius = 8 + "px";
pauseButton.style.zIndex = 1000;
pauseButton.style.background = "rgb(0, 0,
0)";
pauseButton.style.fontSize = 20 + "px";
pauseButton.style.fontWeight = "bold";
pauseButton.style.color = "rgb(255, 255,
255)";
pauseButton.innerHTML = "Pause Button";
pauseButton.onmouseover = function()
{
pauseButton.style.color = "rgb(0, 255,
255)";
};
pauseButton.onmouseout = function()
{
pauseButton.style.color = "rgb(255, 255,
255)";
};
pauseButton.onclick = function()
{
let theVideo =
document.querySelectorAll("video");
theVideo.pause();
};
document.body.append(pauseButton);
}
createPausePlayButtons();
}());
javascript:(
/* createElement Video, play, pause, back,
forward, Mute, UnMute */
function()
{
function createVideoControls()
{
let thePaddingLeft = 10;
let thePaddingRight = 10;
let thePaddingTop = 5;
let thePaddingBottom = 5;
let theMargin = 1;
let theBorderRadius = 8;
let theZIndex = 1000;
let theFontSize = 16;
let theTextColor = "rgb(255, 255, 255)";
let theBackgroundColor = "rgba(0, 0, 0,
0.3)";
let theBorderColor = "rgba(255, 255, 255,
0.3)";
let theFontWeight = "bold";
/*----*/
let mainDiv =
document.createElement("div");
mainDiv.style.position = "absolute";
mainDiv.style.left = 5 + "px";
mainDiv.style.top = 70 + "px";
mainDiv.style.display = "flex";
mainDiv.style.flexDirection = "column";
document.body.append(mainDiv);
/*----*/
let playButton =
document.createElement("button");
playButton.id = "playButton";
playButton.style.paddingLeft =
thePaddingLeft + "px";
playButton.style.paddingRight =
thePaddingRight + "px";
playButton.style.paddingTop =
thePaddingTop + "px";
playButton.style.paddingBottom =
thePaddingBottom + "px";
playButton.style.margin = theMargin + "px";
playButton.style.borderRadius =
theBorderRadius + "px";
playButton.style.borderColor =
theBorderColor;
playButton.style.zIndex = theZIndex;
playButton.style.background =
theBackgroundColor;
playButton.style.fontSize = theFontSize +
"px";
playButton.style.fontWeight =
theFontWeight;
playButton.style.color = theTextColor;
playButton.innerHTML = "Play";
playButton.onmouseover = function()
{
playButton.style.color = "rgb(0, 255,
255)";
};
playButton.onmouseout = function()
{
playButton.style.color = theTextColor;
};
playButton.onclick = function()
{
let theVideo =
document.querySelector("video");
theVideo.play();
};
mainDiv.append(playButton);
/*----*/
let pauseButton =
document.createElement("button");
pauseButton.id = "pauseButton";
pauseButton.style.paddingLeft =
thePaddingLeft + "px";
pauseButton.style.paddingRight =
thePaddingRight + "px";
pauseButton.style.paddingTop =
thePaddingTop + "px";
pauseButton.style.paddingBottom =
thePaddingBottom + "px";
pauseButton.style.margin = theMargin +
"px";
pauseButton.style.borderRadius =
theBorderRadius + "px";
pauseButton.style.borderColor =
theBorderColor;
pauseButton.style.zIndex = theZIndex;
pauseButton.style.background =
theBackgroundColor;
pauseButton.style.fontSize = theFontSize +
"px";
pauseButton.style.fontWeight =
theFontWeight;
pauseButton.style.color = theTextColor;
pauseButton.innerHTML = "Pause";
pauseButton.onmouseover = function()
{
pauseButton.style.color = "rgb(0, 255,
255)";
};
pauseButton.onmouseout = function()
{
pauseButton.style.color = theTextColor;
};
pauseButton.onclick = function()
{
let theVideo =
document.querySelector("video");
theVideo.pause();
};
mainDiv.append(pauseButton);
/*----*/
let backButton =
document.createElement("button");
backButton.id = "backButton";
backButton.style.paddingLeft =
thePaddingLeft + "px";
backButton.style.paddingRight =
thePaddingRight + "px";
backButton.style.paddingTop =
thePaddingTop + "px";
backButton.style.paddingBottom =
thePaddingBottom + "px";
backButton.style.margin = theMargin +
"px";
backButton.style.borderRadius =
theBorderRadius + "px";
backButton.style.borderColor =
theBorderColor;
backButton.style.zIndex = theZIndex;
backButton.style.background =
theBackgroundColor;
backButton.style.fontSize = theFontSize +
"px";
backButton.style.fontWeight =
theFontWeight;
backButton.style.color = theTextColor;
backButton.innerHTML = "Back";
backButton.onmouseover = function()
{
backButton.style.color = "rgb(0, 255,
255)";
};
backButton.onmouseout = function()
{
backButton.style.color = theTextColor;
};
backButton.onclick = function()
{
let theVideo =
document.querySelector("video");
theVideo.currentTime += -2;
};
mainDiv.append(backButton);
/*----*/
let forwardButton =
document.createElement("button");
forwardButton.id = "forwardButton";
forwardButton.style.paddingLeft =
thePaddingLeft + "px";
forwardButton.style.paddingRight =
thePaddingRight + "px";
forwardButton.style.paddingTop =
thePaddingTop + "px";
forwardButton.style.paddingBottom =
thePaddingBottom + "px";
forwardButton.style.margin = theMargin +
"px";
forwardButton.style.borderRadius =
theBorderRadius + "px";
forwardButton.style.borderColor =
theBorderColor;
forwardButton.style.zIndex = theZIndex;
forwardButton.style.background =
theBackgroundColor;
forwardButton.style.fontSize = theFontSize
+ "px";
forwardButton.style.fontWeight =
theFontWeight;
forwardButton.style.color = theTextColor;
forwardButton.innerHTML = "Forward";
forwardButton.onmouseover = function()
{
forwardButton.style.color = "rgb(0, 255,
255)";
};
forwardButton.onmouseout = function()
{
forwardButton.style.color = theTextColor;
};
forwardButton.onclick = function()
{
let theVideo =
document.querySelector("video")[0];
theVideo.currentTime += 2;
};
mainDiv.append(forwardButton);
/*----*/
let speedButton =
document.createElement("button");
speedButton.id = "speedButton";
speedButton.style.paddingLeft =
thePaddingLeft + "px";
speedButton.style.paddingRight =
thePaddingRight + "px";
speedButton.style.paddingTop =
thePaddingTop + "px";
speedButton.style.paddingBottom =
thePaddingBottom + "px";
speedButton.style.margin = theMargin +
"px";
speedButton.style.borderRadius =
theBorderRadius + "px";
speedButton.style.borderColor =
theBorderColor;
speedButton.style.zIndex = theZIndex;
speedButton.style.background =
theBackgroundColor;
speedButton.style.fontSize = theFontSize +
"px";
speedButton.style.fontWeight =
theFontWeight;
speedButton.style.color = theTextColor;
speedButton.innerHTML = "Speed";
speedButton.onmouseover = function()
{
speedButton.style.color = "rgb(0, 255,
255)";
};
speedButton.onmouseout = function()
{
speedButton.style.color = theTextColor;
};
speedButton.onclick = function()
{
let video =
document.querySelector("video");
mainDiv.append(speedButton);
/*----*/
let muteButton =
document.createElement("button");
muteButton.id = "muteButton";
muteButton.style.paddingLeft =
thePaddingLeft + "px";
muteButton.style.paddingRight =
thePaddingRight + "px";
muteButton.style.paddingTop =
thePaddingTop + "px";
muteButton.style.paddingBottom =
thePaddingBottom + "px";
muteButton.style.margin = theMargin +
"px";
muteButton.style.borderRadius =
theBorderRadius + "px";
muteButton.style.borderColor =
theBorderColor;
muteButton.style.zIndex = theZIndex;
muteButton.style.background =
theBackgroundColor;
muteButton.style.fontSize = theFontSize +
"px";
muteButton.style.fontWeight =
theFontWeight;
muteButton.style.color = theTextColor;
muteButton.innerHTML = "Mute";
muteButton.onmouseover = function()
{
muteButton.style.color = "rgb(0, 255,
255)";
};
muteButton.onmouseout = function()
{
muteButton.style.color = theTextColor;
};
muteButton.onclick = function()
{
document.querySelector("video").muted =
true;
};
mainDiv.append(muteButton);
/*----*/
let unmuteButton =
document.createElement("button");
unmuteButton.id = "unmuteButton";
unmuteButton.style.paddingLeft =
thePaddingLeft + "px";
unmuteButton.style.paddingRight =
thePaddingRight + "px";
unmuteButton.style.paddingTop =
thePaddingTop + "px";
unmuteButton.style.paddingBottom =
thePaddingBottom + "px";
unmuteButton.style.margin = theMargin +
"px";
unmuteButton.style.borderRadius =
theBorderRadius + "px";
unmuteButton.style.borderColor =
theBorderColor;
unmuteButton.style.zIndex = theZIndex;
unmuteButton.style.background =
theBackgroundColor;
unmuteButton.style.fontSize = theFontSize
+ "px";
unmuteButton.style.fontWeight =
theFontWeight;
unmuteButton.style.color = theTextColor;
unmuteButton.innerHTML = "Unmute";
unmuteButton.onmouseover = function()
{
unmuteButton.style.color = "rgb(0, 255,
255)";
};
unmuteButton.onmouseout = function()
{
unmuteButton.style.color = theTextColor;
};
unmuteButton.onclick = function()
{
document.querySelector("video").muted
= false;
};
mainDiv.append(unmuteButton);
}
createVideoControls();
}());
javascript:(
/* Show elements of certain class name on
https://CollegeOfScripting.weebly.com */
function()
{
function showData()
{
let nameList =
document.querySelectorAll(".buttonStyle");
theNames += nameList[x].textContent;
theNames += "\n";
}
return theNames.toString();
}
console.log(showData());
alert(showData());
}());
/*
This Bookmarklet is designed to work ONLY on
https://CollegeOfScripting.weebly.com
Right Click on the buttons, such as the
JavaScript button and then
Choose Inspect Element
We see that the Element has a css style class
called .buttonStyle
We use the dot syntax before the class name.
The css style class name is .buttonStyle
Inspecting an Element
After Right Clicking on the Button and choosing
Inspect Element, the Inspector Opens and
allows us to see the name of the class of that
Button.
In this case, the buttons of this Weebly Website
have a class called
buttonStyle
Thus, we simply use that class name, when we
want to reference only elements that use that
class. This allows us to examine any webpage
and inspect any element to find their class
name, which therefore allows us the ability to
reference any elements on the page that use that
class.
*/
Inspecting an Element
return solarWindSpeed;
}
function showData()
{
let solarWindSpeed = "Solar Wind Speed: "
+ getSolarWindSpeed() + " km/second";
console.log(solarWindSpeed);
alert(solarWindSpeed);
}
showData();
}());
https://www.swpc.noaa.gov
<li>
<span class="summary-field-label">Solar Wind Speed:</span>
<span id="WindSpeed" class="summary-field-value">354</span>
km/sec
</li>
/*
Solar Wind Speed: 354 km/second
return solarWindSpeed;
}
function showData()
{
let solarWindSpeed = "Solar Wind Speed: "
+ getSolarWindSpeed() + " km/second";
console.log(solarWindSpeed);
}
showData();
}());
/*
We go to https://www.swpc.noaa.gov and then
activate this script.
function getSolarWindSpeed()
{
let solarWindSpeed =
document.querySelector("#WindSpeed").textCo
ntent;
console.log(JSON.stringify(solarWindArray));
console.log(JSON.stringify(solarWindArray));
}, 60 * 1000);
}());
/*
When activated on https://www.swpc.noaa.gov
this script will get the Solar Wind Speed every 1
minute and add the solar wind speed to the
array, in addition to the date and time.
function getSolarWindSpeed()
{
let solarWindSpeed =
document.querySelector("#WindSpeed").textCo
ntent;
return {
date: dateLocal,
speed: solarWindSpeed
};
}
console.log(JSON.stringify(solarWindArray));
console.log(JSON.stringify(solarWindArray));
}, 60 * 1000);
}());
function showCounterData()
{
console.log(counter);
counter += 1;
}
setInterval(showCounterData, 5000);
}());
javascript:(
/* Timer - Every 1 Second, Count Up */
function()
{
let counter = 0;
function updateIt()
{
counter += 1;
return counter;
}
function createCounterDiv()
{
let ourDiv = document.createElement("div");
ourDiv.id = "theDiv";
ourDiv.style.position = "absolute";
ourDiv.style.left = 20 + "px";
ourDiv.style.top = 150 + "px";
ourDiv.style.width = 100 + "px";
ourDiv.style.height = 25 + "px";
ourDiv.style.padding = 10 + "px";
ourDiv.style.backgroundColor = "rgb(0, 0,
0)";
ourDiv.style.fontSize = 20 + "px";
ourDiv.style.color = "rgb(255, 255, 255)";
ourDiv.innerHTML = updateIt();
document.body.append(ourDiv);
}
setInterval(createCounterDiv, 1000);
}());
javascript:(
/* Timer - Every 1 Second, Count Down,
clearInterval */
function()
{
let counter = prompt("Enter Count Down Start
Time");
function countDown()
{
counter -= 1;
if (counter == 0)
{
clearInterval(ourTimer);
}
return counter;
}
function createCounterDiv()
{
let ourDiv = document.createElement("div");
ourDiv.id = "theDiv";
ourDiv.style.position = "absolute";
ourDiv.style.left = 100 + "px";
ourDiv.style.top = 100 + "px";
ourDiv.style.padding = 10 + "px";
ourDiv.style.borderRadius = 8 + "px";
ourDiv.style.backgroundColor = "rgb(0, 0, 0)";
ourDiv.style.fontSize = 25 + "px";
ourDiv.style.fontWeight = "bold";
ourDiv.style.color = "rgb(255, 255, 255)";
ourDiv.innerHTML = countDown();
document.body.append(ourDiv);
}
let ourTimer = setInterval(createCounterDiv,
1000);
}());
javascript:(
/* Array of Objects - JSON.stringify */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showData(whichArray)
{
console.log(whichArray);
console.log(JSON.stringify(whichArray));
}
showData(people);
}());
/*
Here is the Output
console.log(people);
0: Object { name: "Melissa", date: "1980/03/01" }
console.log(JSON.stringify(people));
[{"name":"Melissa","date":"1980/03/01"},
{"name":"Tabitha","date": "1983/04/05"}]
*/
javascript:(
/* Array of Objects - for loop */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showData(whichArray)
{
for (let x = 0; x < whichArray.length; x++)
{
console.log(whichArray[x]);
}
}
showData(people);
}());
/*
*/
javascript:(
/* Array of Objects - while loop */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showData(whichArray)
{
let x = 0;
x += 1;
}
}
showData(people);
}());
/*
{ name: 'Melissa', date: '1980/03/01' }
{ name: 'Tabitha', date: '1983/04/05' }
*/
javascript:(
/* Array of Objects - Names only */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showData(whichArray)
{
let x = 0;
x += 1;
}
}
showData(people);
}());
/*
Melissa
Tabitha
*/
javascript:(
/* Array of Objects - Dates only */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
let x = 0;
while (x < people.length)
{
console.log(people[x].date);
x += 1;
}
}());
/*
1980/03/01
1983/04/05
*/
javascript:(
/* Array of Objects - for loop */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showData(whichArray)
{
let output = 'Name\t\tDate\n';
for (let x = 0; x < whichArray.length; x++)
{
output = output + whichArray[x].name;
output += "\t";
output += whichArray[x].date;
output += "\n";
}
console.log(output);
alert(output);
}
about:newtab
Name Date
showData(people); Melissa 1980/03/01
Tabitha 1983/04/05 OK
}());
javascript:(
/* Array of Objects - First Letter Initial */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showFirstLetterOfName(whichArray)
{
let x = 0
x += 1;
}
}
showFirstLetterOfName(people);
}());
/*
M
T
*/
javascript:(
/* Array of Objects - First 3 Letter Initials */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
}
];
function showData(whichArray)
{
let x = 0;
x += 1;
}
}
showData(people);
}());
/*
Mel
Tab */
javascript:(
/* Array of Objects - Filter by Year */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
},
{
name: 'Jane',
date: '1987/08/12'
}
];
function showData(whichArray)
{
for (let x = 0; x < whichArray.length; x++)
{
if (whichArray[x].date >= "1981")
{
console.log(whichArray[x].name + "\n"
+ whichArray[x].date);
}
}
}
sortByDate(people, "up");
showData(people);
}());
/*
Tabitha
1983/04/05
Jane
1987/08/12
*/
javascript:(
/* Array of Objects - Filter by Year and Month */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
},
{
name: 'Joan',
date: '1983/05/17'
},
{
name: 'Jane',
date: '1987/08/12'
}
];
function showData(whichArray)
{
for (let x = 0; x < whichArray.length; x++)
{
if (whichArray[x].date >= "1983/05")
{
console.log(whichArray[x].name + "\n"
+ whichArray[x].date);
}
}
}
sortByDate(people, "up");
showData(people);
}());
/*
Joan
1983/05/17
Jane
1987/08/12
*/
javascript:(
/* Array of Objects - Filter by Year, Month and
Day */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01',
},
{
name: 'Tabitha',
date: '1983/04/05'
},
{
name: 'Joan',
date: '1983/05/17'
},
{
name: 'Jane',
date: '1987/08/12'
}
];
function showData(whichArray)
{
for (let x = 0; x < whichArray.length; x++)
{
if (whichArray[x].date == "1983/04/05")
{
console.log(whichArray[x].name + "\n"
+ whichArray[x].date);
}
}
}
sortByDate(people, "up");
showData(people);
}());
/*
Tabitha
1983/04/05
*/
javascript:(
/* Array of Objects - Filter by Year, Month, Day
and Time */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01 12:00PM',
},
{
name: 'Tabitha',
date: '1983/04/05 2:57PM'
},
{
name: 'Jennifer',
date: '1983/05/17 3:45PM'
},
{
name: 'Joan',
date: '1983/05/17 4:07PM'
},
{
name: 'Jane',
date: '1987/08/12 8:23PM'
}
];
function showData(whichArray)
{
for (let x = 0; x < whichArray.length; x++)
{
if (whichArray[x].date >= "1983/05/17
3:50PM")
{
console.log(whichArray[x].name + "\n"
+ whichArray[x].date);
}
}
}
sortByDate(people, "up");
showData(people);
}());
/*
Joan
1983/05/17 4:07PM
Jane
1987/08/12 8:23PM
*/
javascript:(
/* Array of Objects - Filter Date A to Date B,
YYYY/MM/DD */
function()
{
let people =
[
{
name: 'Melissa',
date: '1980/03/01 12:00PM',
},
{
name: 'Tabitha',
date: '1983/04/05 2:57PM'
},
{
name: 'Jennifer',
date: '1983/05/17 3:45PM'
},
{
name: 'Joan',
date: '1983/05/17 4:07PM'
},
{
name: 'Jane',
date: '1987/08/12 8:23PM'
}
];
function showData(whichArray)
{
for (let x = 0; x < whichArray.length; x++)
{
if (whichArray[x].date >= "1983/05/17
3:45PM" && whichArray[x].date <= "1983/05/17
4:00PM")
{
console.log(whichArray[x].name + "\n"
+ whichArray[x].date);
}
}
}
sortByDate(people, "up");
showData(people);
}());
/*
Jennifer
1983/05/17 3:45PM
*/
javascript:(
/* Array of Objects - Special way to show keys
and values */
function()
{
let people =
[
{
name: 'Melissa',
date: '2021/04/01',
},
{
name: 'Tabitha',
date: '2021/04/05'
}
];
}());
/*
we use a for loop to iterate through this array
and access both the key and value for each
property in the object
name: Melissa
date: 2021/04/01
name: Tabitha
date: 2021/04/05
*/
javascript:(
/* Array of Objects with Nested Arrays */
function()
{
function showData()
{
let data =
[
{
name: 'James',
age: 30,
hobbies: ['Gardening', 'Gaming']
},
{
name: 'Joan',
age: 25,
hobbies: ['Hiking', 'Painting']
}
];
let message = 'Array of Objects:\n';
console.log(message);
alert(message);
}
showData();
}());
javascript:(
/* Array of Objects - Show Data on Rows of Divs
*/
function()
{
function showData()
{
let data =
[
{
name: 'Item 1',
description: 'Description 1'
},
{
name: 'Item 2',
description: 'Description 2'
},
{
name: 'Item 3',
description: 'Description 3'
},
{
name: 'Item 4',
description: 'Description 4'
},
{
name: 'Item 5',
description: 'Description 5'
},
{
name: 'Item 6',
description: 'Description 6'
},
{
name: 'Item 7',
description: 'Description 7'
},
{
name: 'Item 8',
description: 'Description 8'
},
{
name: 'Item 9',
description: 'Description 9'
},
];
dataDiv.innerHTML = '<h3>' +
object.name + '</h3>' + '<p>' + object.description
+ '</p>';
container.append(dataDiv);
}
}());
javascript:(
/* Array of Objects - map, filter, reduce - Finds
Ages Over Specified Age */
function()
{
function
showNamesOverSpecifiedAge(whichAge)
{
let data =
[
{
name: 'John',
age: 30
},
{
name: 'Jane',
age: 25
},
{
name: 'James',
age: 35
},
{
name: 'Alice',
age: 28
},
{
name: 'Joan',
age: 40
}
];
/*----*/
showNamesOverSpecifiedAge(30);
}());
javascript:(
/* Array of Objects - Emoji Fun */
function()
{
let funObjects =
[
{
},
name: "Smiling Face",
description: "A face with a big smile 😃 ",
},
name: "Big Hat",
description: "A big hat 🎩
",
},
name: "SunShades",
description: "A pair of sunshades 😎 ",
];
console.log(message);
alert(message);
}());
javascript:(
/* Array of Objects - Random Object –
Programming Languages */
function()
{
let programmingFacts =
[
{
name: "C",
fact: "Invented in 1972",
},
{
name: "C++",
fact: "Invented in 1985",
},
{
name: "JavaScript",
fact: "Invented in 1995",
}
];
function generateRandomFact(whichArray)
{
let randomIndex = Math.floor(Math.random()
* whichArray.length);
console.log(message);
alert(message);
}
generateRandomFact(programmingFacts);
}());
javascript:(
/* Array of Objects - Random Object - Periodic
Elements */
function()
{
let periodicTable =
[
{
symbol: "H",
name: "Hydrogen",
atomicNumber: 1,
},
{
symbol: "He",
name: "Helium",
atomicNumber: 2,
},
{
symbol: "Li",
name: "Lithium",
atomicNumber: 3,
},
{
symbol: "Be",
name: "Beryllium",
atomicNumber: 4,
}
];
function generateRandomFact(whichArray)
{
let randomIndex = Math.floor(Math.random()
* whichArray.length);
console.log(message);
alert(message);
}
generateRandomFact(periodicTable);
}());
javascript:(
/* Array of Objects - Calculate the Average Score
*/
function()
{
function calculateAverageScore()
{
let students =
[
{
name: "Alice",
score: 85
},
{
name: "Bob",
score: 92
},
{
name: "James",
score: 78
},
{
name: "David",
score: 88
},
{
name: "Jennifer",
score: 95
},
];
function calculateAverage(scores)
{
let total = 0;
calculateAverageScore();
}());
javascript:(
/* Array of Objects - Calculate Average Score,
Standard Deviation */
function()
{
let students =
[
{
name: "Alice",
score: 85
},
{
name: "Bob",
score: 92
},
{
name: "Jennifer",
score: 78
},
{
name: "David",
score: 88
},
{
name: "Joan",
score: 95
},
];
function calculateAverage(scores)
{
let total = 0;
function calculateStandardDeviation(scores)
{
let average = calculateAverage(scores);
let variance = 0;
let standardDeviation =
calculateStandardDeviation(students);
}());
javascript:(
/* Array of Objects - Find Max/Min Temperature */
function()
{
function calculateMinMaxTemperature()
{
let cities =
[
{
name: "New York",
temperature: 90
},
{
name: "Los Angeles",
temperature: 82
},
{
name: "Chicago",
temperature: 76
},
{
name: "Boston",
temperature: 95
},
{
name: "Denver",
temperature: 87
},
];
function findMaxTemperature(whichArray)
{
let max = whichArray[0].temperature;
function findMinTemperature(whichArray)
{
let min = whichArray[0].temperature;
let minTemperature =
findMinTemperature(cities);
calculateMinMaxTemperature();
}());
javascript:(
/* Array of Objects - Calculate Sales Total */
function()
{
function calculateSalesTotal()
{
let products =
[
{
name: "Store A",
sales: 250
},
{
name: "Store B",
sales: 180
},
{
name: "Store C",
sales: 320
},
{
name: "Store D",
sales: 420
},
];
function calculateTotalSales(salesData)
{
let total = 0;
return total;
}
alert(calculateSalesTotal());
}());
javascript:(
/* Array of Objects - Count occurrences of each
item */
function()
{
function countOccurrencesOfEachItem()
{
let food =
[
{
name: "Apple",
quantity: 3
},
{
name: "Banana",
quantity: 2
},
{
name: "Strawberry",
quantity: 4
},
{
name: "Apple",
quantity: 2
},
{
name: "Pear",
quantity: 3
},
{
name: "Banana",
quantity: 1
},
];
function countFruitOccurrences(items)
{
let fruitCounts = {};
if (fruitCounts[itemName])
{
fruitCounts[itemName] +=
items[x].quantity;
}
else
{
fruitCounts[itemName] =
items[x].quantity;
}
}
return fruitCounts;
}
let fruitKeys =
Object.keys(fruitOccurrences);
console.log(message);
alert(message);
}
countOccurrencesOfEachItem();
}());
/*
Fruit Occurrences:
Apple: 5
Banana: 3
Strawberry: 4
Pear: 3
*/
javascript:(
/* Links - List and Count */
function()
{
function listLinksAndCount()
{
let links = document.links;
if (linkCount === 0)
{
alert('No links found on the page');
}
else
{
let linkSources = [];
console.log(data);
alert(data);
}
}
listLinksAndCount();
}());
javascript:(
/* Element - List and Count Specified Type */
function()
{
function listAndCount(elementType)
{
let elements =
document.getElementsByTagName(elementType
);
if (elementCount === 0)
{
alert('No ' + elementType + 's found on
this page');
}
else
{
let elementContents = [];
for (let x = 0; x < elementCount; x++)
{
elementContents.push(elements[x].textContent);
}
console.log(data);
alert(data);
}
}
listAndCount('a');
}());
javascript:(
/* Bouncing Ball - Linear Motion - Bounces
Up/Down - No Trigonometry required */
function()
{
function createBallWithMotion()
{
let ball = document.createElement('div');
ball.id = 'ball';
ball.style.position = "absolute";
ball.style.width = "50px";
ball.style.height = "50px";
ball.style.borderRadius = "50%";
ball.style.margin = "0px";
ball.style.overflow = "hidden";
ball.style.backgroundColor = "aqua";
document.body.append(ball);
let speed = 2;
function animate()
{
position += direction * speed;
let animationFrameId001;
function gameLoop()
{
animate();
animationFrameId001 =
requestAnimationFrame(gameLoop);
}
gameLoop();
}
createBallWithMotion();
}());
javascript:(
/* Bouncing Ball - Linear Motion - Starts at an
Angle - No Trigonometry Required */
function()
{
function createBallWithMotion()
{
let ball = document.createElement('div');
ball.id = 'ball';
ball.style.position = "absolute";
ball.style.width = "50px";
ball.style.height = "50px";
ball.style.borderRadius = "50%";
ball.style.margin = "0px";
ball.style.overflow = "hidden";
ball.style.backgroundColor = "aqua";
document.body.append(ball);
let x = 0;
let y = 0;
let dx = 5;
let dy = 5;
function animate()
{
x += dx;
y += dy;
let animationFrameId001;
function gameLoop()
{
animate();
animationFrameId001 =
requestAnimationFrame(gameLoop);
}
gameLoop();
}
createBallWithMotion();
}());
javascript:(
/* Bouncing Ball - Linear Motion - Starts at Angle
- Trigonometry Angle Calculation */
function()
{
function createBouncingBall()
{
let ball = document.createElement('div');
ball.id = 'ball';
ball.style.position = "absolute";
ball.style.width = "50px";
ball.style.height = "50px";
ball.style.borderRadius = "50%";
ball.style.margin = "0px";
ball.style.overflow = "hidden";
ball.style.backgroundColor = "aqua";
document.body.append(ball);
let positionX = 0;
let positionY = 0;
function animate()
{
positionX += xSpeed;
positionY += ySpeed;
let animationFrameId001;
function gameLoop()
{
animate();
animationFrameId001 =
requestAnimationFrame(gameLoop);
}
gameLoop();
}
createBouncingBall();
}());
javascript:(
/* Bouncing Circles - Linear Motion - Starts at
Angle - No Trigonometry Required */
function()
{
let circles = [];
function getRandomPosition()
{
let x = Math.floor(Math.random() *
window.innerWidth);
let y = Math.floor(Math.random() *
window.innerHeight);
return {
x: x,
y: y
};
}
circle.dx = Math.random() * 4 - 2;
circle.dy = Math.random() * 4 - 2;
document.body.append(circle);
circles.push(circle);
}
function animate()
{
for (let x = 0; x < circles.length; x++)
{
let circle = circles[x];
circle.style.left = (parseInt(circle.style.left)
+ circle.dx) + 'px';
circle.style.top =
(parseInt(circle.style.top) + circle.dy) + 'px';
if (parseInt(circle.style.left) <= 0 ||
parseInt(circle.style.left) >= window.innerWidth -
20)
{
circle.dx *= -1;
}
if (parseInt(circle.style.top) <= 0 ||
parseInt(circle.style.top) >= window.innerHeight
- 20)
{
circle.dy *= -1;
}
}
}
let animationFrameId001;
function gameLoop()
{
animate();
animationFrameId001 =
requestAnimationFrame(gameLoop);
}
gameLoop();
}());
javascript:(
/* Airplane Projectile Simulated Drop of
projectile from airplane where user clicks */
function()
{
let airplane = document.createElement('div');
airplane.style.position = 'absolute';
airplane.style.left = '-50px';
airplane.style.top = '50px';
airplane.style.width = '50px';
airplane.style.height = '20px';
airplane.style.backgroundColor = 'blue';
airplane.style.transition = 'all 2s linear';
document.body.append(airplane);
/*----*/
document.onclick = function(event)
{
if (!flying)
{
flying = true;
airplane.style.transform = 'translate(' +
window.innerWidth + 'px, 0)';
setTimeout(function()
{
let x = event.clientX;
let y = event.clientY;
projectile.style.left = x + 'px';
projectile.style.top = '25px';
projectile.style.display = 'block';
/* projectile path */
projectile.style.transform = 'translateY('
+ (y - 25) + 'px)';
}, 1000);
}
};
}());
/*
When a person left clicks their mouse on the
screen an airplane will fly to the right and
simulate dropping a projectile below, which will
remain on the screen.
*/
javascript:(
/* Airplane - Projectile - Realistic - Projectile
drops from bottom middle of airplane */
function()
{
let airplane = document.createElement('div');
airplane.id = "airplane";
airplane.style.position = 'absolute';
airplane.style.left = '-50px';
airplane.style.top = '50px';
airplane.style.width = '50px';
airplane.style.height = '20px';
airplane.style.backgroundColor = 'blue';
airplane.style.transition = 'all 2s linear';
document.body.append(airplane);
/*----*/
document.onclick = function(event)
{
if (!flying)
{
flying = true;
function animateProjectile(timestamp)
{
if (!startTime)
{
startTime = timestamp;
}
}());
javascript:(
/* Mouse Arrow Effect - Circles */
function()
{
function changeMouseArrow()
{
const theEffect =
document.createElement('style');
theEffect.innerText = `
*{
cursor: url('data:image/svg+xml;utf8,<svg
xmlns="http://www.w3.org/2000/svg" width="32"
height="32" viewBox="0 0 24 24"><circle
cx="12" cy="12" r="10" stroke="white" stroke-
width="2" fill="transparent"/><circle cx="12"
cy="12" r="6" stroke="white" stroke-width="2"
fill="transparent"/><circle cx="12" cy="12" r="2"
fill="white"/></svg>'), auto !important;
}`;
document.head.append(theEffect);
}
changeMouseArrow();
}());
javascript:(
/* Animate Words Typing Effect */
function()
{
function animateText()
{
let text = "Hi Everyone";
let x = 0;
let animationSpeed = 400;
let textDiv =
document.createElement("div");
textDiv.style.position = "fixed";
textDiv.style.top = "50%";
textDiv.style.left = "50%";
textDiv.style.transform = "translate(-50%, -
50%)";
textDiv.style.fontSize = "25px";
document.body.append(textDiv);
let animation = setInterval(function()
{
if (x < text.length)
{
textDiv.textContent = text.substring(0,
x + 1);
x++;
}
else
{
clearInterval(animation);
}
}, animationSpeed);
}
animateText();
}());
/* displays a text of "Hi Everyone" with an
animation. Each letter appears one by one. */
javascript:(
/* Detect which Web Browser is being used */
function()
{
function detectWebBrowser()
{
if
(navigator.userAgent.toLowerCase().indexOf('fir
efox') !== -1)
{
return 'You are using Firefox';
}
if
(navigator.userAgent.toLowerCase().indexOf('ch
rome') !== -1)
{
return 'You are using Chrome';
}
if
(navigator.userAgent.toLowerCase().indexOf('sa
fari') !== -1)
{
return 'You are using Safari';
}
console.log(detectWebBrowser());
alert(detectWebBrowser());
}());
javascript:(
/* Pythagorean Theorem */
function()
{
/* create a function to calculate the
hypotenuse length */
function calculateHypotenuse(a, b)
{
return Math.sqrt(a * a + b * b);
}
}());
javascript:(
/* Calculate Factorial */
function()
{
/* create a function to calculate the factorial */
function calculateFactorial(whichNumber)
{
if (whichNumber < 0)
{
return "The factorial is not defined for
negative numbers";
}
else if (whichNumber === 0)
{
return 1;
}
else
{
let factorial = 1;
for (let x = 1; x <= whichNumber; x++)
{
factorial *= x;
}
return factorial;
}
}
}());
javascript:(
/* Calculate Circle Circumference and Area */
function()
{
function calculateCircleProperties()
{
let radius = parseFloat(prompt("Enter the
radius of the circle:"));
alert(
"Radius: " + radius.toFixed(2) + "\n" +
"Area: " + area.toFixed(2) + "\n" +
"Circumference: " +
circumference.toFixed(2)
);
}
else
{
alert("Enter a valid positive number for
the radius.");
}
}
calculateCircleProperties();
}());
javascript:(
/* Button Beep Sound using Oscillator */
function()
{
/* create a button element */
let button = document.createElement('button');
button.textContent = 'Click me for a beep';
oscillator.connect(audioContext.destination);
oscillator.start();
setTimeout(function()
{
oscillator.stop();
}, 100);
});
}());
javascript:(
/* Draggable Square */
function()
{
function createDraggableSquare()
{
let square = document.createElement('div');
square.style.position = 'absolute';
square.style.left = '100px';
square.style.top = '100px';
square.style.width = '50px';
square.style.height = '50px';
square.style.backgroundColor = 'aqua';
square.style.cursor = 'move';
offsetX = event.clientX -
square.getBoundingClientRect().left;
offsetY = event.clientY -
square.getBoundingClientRect().top;
});
y = Math.min(Math.max(y, 0),
window.innerHeight - 50);
square.style.left = x + 'px';
square.style.top = y + 'px';
}
});
document.body.append(square);
}
createDraggableSquare();
}());
javascript:(
/* Drag any element on any webpage */
function()
{
function makePageElementsDraggable()
{
let dragItem = null;
let offsetX;
let offsetY;
document.addEventListener('mousedown',
function(e)
{
dragItem = e.target;
offsetX = e.clientX -
dragItem.getBoundingClientRect().left;
offsetY = e.clientY -
dragItem.getBoundingClientRect().top;
dragItem.style.position = 'absolute';
document.body.append(dragItem);
});
document.addEventListener('mousemove',
function(e)
{
if (dragItem)
{
dragItem.style.left = e.clientX - offsetX
+ 'px';
document.addEventListener('mouseup',
function()
{
dragItem = null;
});
}
makePageElementsDraggable();
}());
javascript:(
/* Newton's First Law of Motion - The Law of
Inertia.*/
function()
{
function createMovingSquare()
{
let box = document.createElement("div");
box.style.position = "absolute";
box.style.top = "50px";
box.style.left = "50px";
box.style.width = "100px";
box.style.height = "100px";
box.style.backgroundColor = "aqua";
document.body.append(box);
/* starting velocity */
let velocity = 1;
function animate()
{
/* move the box horizontally */
box.style.left = parseInt(box.style.left) +
velocity + "px";
function gameLoop()
{
animate();
animationFrameId001 =
requestAnimationFrame(gameLoop);
}
gameLoop();
}
createMovingSquare();
}());
/*
Newton's First Law of Motion - an object will
keep going in its current state of motion unless
an external force acts on it.
function updateDistance()
{
/* update distance */
distance -= speed / 60;
if (distance <= 0)
{
document.getElementById("galactus-
update").innerHTML = "Galactus has arrived!";
clearInterval(interval);
}
else
{
document.getElementById("galactus-
update").innerHTML = "Galactus is " +
distance.toFixed(2) + " miles away.";
}
}
calculateGalactusDistanceToEarth();
}());
javascript:(
/* Calculate Distance of Galactus to Earth and
How Long Until Arrival */
function()
{
function
calculateGalactusDistanceAndTimeToEarth()
{
/* start distance of Galactus to Earth */
let distance = 1000000; /* miles */
function updateDistance()
{
/* update distance */
distance -= speed / 60;
if (distance <= 0)
{
document.getElementById("galactus-
update").innerHTML = "Galactus has arrived!";
clearInterval(interval);
}
else
{
/* calculate time in hours */
let timeInHours = distance / speed;
calculateGalactusDistanceAndTimeToEarth();
}());
javascript:(
/* Square Expands with Each Click */
function()
{
function createExpandingSquare()
{
/* create a square element */
const square =
document.createElement('div');
square.id = "square";
square.style.position = "absolute";
square.style.left = 100 + "px";
square.style.top = 50 + "px";
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'aqua';
square.style.transition = 'width 0.3s, height
0.3s';
square.style.cursor = 'pointer';
/* starting width and height */
let width = 100;
let height = 100;
/*----*/
function updateSquareSize()
{
if (expanding)
{
width += 20;
height += 20;
createExpandingContractingSquare();
}());
javascript:(
/* Square Moves in Square Pattern by Timer */
function()
{
function createSquareMoveInSquarePattern()
{
/* create a square element */
let square = document.createElement('div');
square.style.position = 'absolute';
square.style.left = '20px';
square.style.top = '20px';
square.style.width = '50px';
square.style.height = '50px';
square.style.backgroundColor = 'aqua';
square.style.transition = 'transform 2s';
function moveSquare()
{
if (direction === 0)
{
x += 100;
}
else if (direction === 1)
{
y += 100;
}
else if (direction === 2)
{
x -= 100;
}
else if (direction === 3)
{
y -= 100;
}
square.style.transform = 'translate(' + x +
'px, ' + y + 'px)';
/* update direction */
direction = (direction + 1) % 4;
}
specialEfxBox.onclick = function()
{
let particles = [];
particle.style.left =
specialEfxBox.getBoundingClientRect().left +
randomX + 'px';
particle.style.top =
specialEfxBox.getBoundingClientRect().top +
randomY + 'px';
particles.push(particle);
document.body.append(particle);
}
setTimeout(function()
{
for (let i = 0; i < particles.length; i++)
{
/* remove particles after animation */
particles[i].remove();
}
}, 1000);
};
document.body.append(specialEfxBox);
/*----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes explode {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(2);
}
}`;
document.head.append(style001);
}
makeClickableSpecialEfx();
}());
javascript:(
/* Special Efx - Random Color Squares */
function()
{
function makeClickableSpecialEfx()
{
let specialEfxBox =
document.createElement('div');
specialEfxBox.style.position = 'absolute';
specialEfxBox.style.left = '100px';
specialEfxBox.style.top = '50px';
specialEfxBox.style.width = '50px';
specialEfxBox.style.height = '50px';
specialEfxBox.style.backgroundColor =
'blue';
specialEfxBox.style.cursor = 'pointer';
specialEfxBox.onclick = function()
{
let particles = [];
let amount = 500;
particle.style.left =
specialEfxBox.getBoundingClientRect().left +
randomX + 'px';
particle.style.top =
specialEfxBox.getBoundingClientRect().top +
randomY + 'px';
particles.push(particle);
document.body.append(particle);
}
setTimeout(function()
{
for (let i = 0; i < particles.length; i++)
{
/* remove particles after animation */
particles[i].remove();
}
}, 500);
};
document.body.append(specialEfxBox);
/*----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes explode {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(5);
}
}`;
document.head.append(style001);
}
function getRandomColor()
{
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
}());
javascript:(
/* Special Efx - Circles Random Color and Size */
function()
{
function makeClickableSpecialEfx()
{
let specialEfxBox =
document.createElement('div');
specialEfxBox.style.position = 'absolute';
specialEfxBox.style.left = '100px';
specialEfxBox.style.top = '50px';
specialEfxBox.style.width = '100px';
specialEfxBox.style.height = '100px';
specialEfxBox.style.backgroundColor =
'blue';
specialEfxBox.style.cursor = 'pointer';
specialEfxBox.onclick = function()
{
let particles = [];
let amount = 500;
particle.style.top =
specialEfxBox.getBoundingClientRect().top +
randomY + 'px';
particles.push(particle);
document.body.append(particle);
}
/* hide the original div */
specialEfxBox.style.display = 'none';
setTimeout(function()
{
for (let i = 0; i < particles.length; i++)
{
/* remove particles after animation */
particles[i].remove();
}
}, 500);
};
document.body.append(specialEfxBox);
/*----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes explode {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(5);
}
}`;
document.head.append(style001);
}
function getRandomColor()
{
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
makeClickableSpecialEfx();
}());
javascript:(
/* Special Efx - Circles in a Circle */
function()
{
function makeClickableSpecialEfx()
{
let specialEfxBox =
document.createElement('div');
specialEfxBox.style.position = 'absolute';
specialEfxBox.style.left = '50%';
specialEfxBox.style.top = '50%';
specialEfxBox.style.transform = 'translate(-
50%, -50%)';
specialEfxBox.style.width = '50px';
specialEfxBox.style.height = '50px';
specialEfxBox.style.backgroundColor =
'blue';
/* make it a circle */
specialEfxBox.style.borderRadius = '50%';
specialEfxBox.style.cursor = 'pointer';
specialEfxBox.onclick = function()
{
let particles = [];
let amount = 500;
/*----*/
particles.push(particle);
document.body.append(particle);
}
setTimeout(function()
{
for (let i = 0; i < particles.length; i++)
{
/* remove particles after animation */
particles[i].remove();
}
}, 500);
};
document.body.append(specialEfxBox);
/*----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes explode {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(5);
}
}`;
document.head.append(style001);
}
function getRandomColor()
{
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
makeClickableSpecialEfx();
}());
javascript:(
/* Special Efx - Circle Expands */
function()
{
function makeSpecialEfx()
{
let particles = [];
/*----*/
/*----*/
/*----*/
particles.push(particle);
document.body.append(particle);
}
setTimeout(function()
{
for (let i = 0; i < particles.length; i++)
{
/* remove particles after animation */
particles[i].remove();
}
}, 1000);
}
/*-----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes explode {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(5);
}
}`;
document.head.append(style001);
makeSpecialEfx();
}());
/*
The Circle expands with a smooth animation.
*/
javascript:(
/* Special Efx - Circle Expands to Concentric
Circles */
function()
{
function makeSpecialEfx()
{
let circles = [];
/*----*/
/*----*/
circles.push(circle);
document.body.append(circle);
}
setTimeout(function()
{
for (let i = 0; i < circles.length; i++)
{
/* remove circles after animation */
circles[i].remove();
}
}, 1000);
}
/*----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes expandCircle {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(1.5);
}
}`;
document.head.append(style001);
makeSpecialEfx();
}());
javascript:(
/* Special Efx - Array of Objects - Random
Choice */
function()
{
function generateSpecialEffects()
{
let specialEfx =
[
{
name: 'Effect 1',
color: 'aqua',
size: 50,
},
{
name: 'Effect 2',
color: 'yellow',
size: 200,
},
{
name: 'Effect 3',
color: 'blue',
size: 400,
},
];
function createRandomEfx()
{
let whichArray = specialEfx;
let randomIndex =
Math.floor(Math.random() * whichArray.length);
let effectChosen =
whichArray[randomIndex];
/*----*/
let particle =
document.createElement('div');
particle.style.position = 'absolute';
particle.style.width = effectChosen.size +
'px';
particle.style.height = effectChosen.size +
'px';
particle.style.borderRadius = '50%';
particle.style.backgroundColor =
effectChosen.color;
particle.style.animation = 'expandCircle
1s ease-in-out';
/*----*/
/*----*/
/*----*/
document.body.append(particle);
setTimeout(function()
{
/* remove the particle after animation */
particle.remove();
}, 700);
}
/*----*/
let style001 =
document.createElement('style');
style001.innerHTML = `
@keyframes expandCircle {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(1.5);
}
}`;
document.head.append(style001);
generateSpecialEffects();
}());
javascript:(
/* Cards - Shuffle Deck - Create the deck as an
Array */
function()
{
function shuffleDeck()
{
const suits = ['Hearts', 'Diamonds', 'Clubs',
'Spades'];
const values = ['2', '3', '4', '5', '6', '7', '8', '9',
'10', 'Jack', 'Queen', 'King', 'Ace'];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
}
let shuffledDeck = shuffleDeck();
/* show as objects */
console.log(shuffledDeck);
/* show as JSON */
console.log(JSON.stringify(shuffledDeck));
/* show as JSON */
alert(JSON.stringify(shuffledDeck));
}());
const values = ['2', '3', '4', '5', '6', '7', '8', '9',
'10', 'Jack', 'Queen', 'King', 'Ace'];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
}
let shuffledDeck = shuffleDeck();
}());
javascript:(
/* Cards - Shuffle Deck - Create the deck as an
Array of Objects */
function()
{
function shuffleDeck()
{
const suits = ['Hearts', 'Diamonds', 'Clubs',
'Spades'];
const values = ['2', '3', '4', '5', '6', '7', '8', '9',
'10', 'Jack', 'Queen', 'King', 'Ace'];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
}
/* show as objects */
console.log(shuffledDeck);
/* show as JSON */
console.log(JSON.stringify(shuffledDeck));
/* show as JSON */
alert(JSON.stringify(shuffledDeck));
}());
/* show as JSON */
javascript:(
/* Cards - Shuffle Deck - Create the deck as an
Array of Objects - Rows of 4 */
function()
{
function shuffleDeck()
{
const suits = ['Hearts', 'Diamonds', 'Clubs',
'Spades'];
const values = ['2', '3', '4', '5', '6', '7', '8', '9',
'10', 'Jack', 'Queen', 'King', 'Ace'];
deck[i] = deck[j];
deck[j] = temp;
}
return deck;
}
/* show as objects */
console.log(shuffledDeck);
/* show as JSON */
console.log(JSON.stringify(shuffledDeck));
/*----*/
}());
javascript:(
/* Trigonometry - Convert Degrees To Radians */
function()
{
function getAngleInDegree()
{
let angle = parseFloat(prompt("Enter an
angle in degrees:"));
return angle;
}
function convertDegreeToRadian(angle)
{
if (!isNaN(angle))
{
/* angle in degree converted to radian */
let radians = angle * (Math.PI / 180);
return radians;
}
else
{
alert("Angle wasn't entered in numbers");
}
}
let result =
convertDegreeToRadian(getAngleInDegree());
console.log(result);
alert(result);
}());
javascript:(
/* Trigonometry - Sine */
function()
{
function getAngleInDegree()
{
let angle = parseFloat(prompt("Enter an
angle in degrees:"));
return angle;
}
function convertDegreeToRadian(angle)
{
if (!isNaN(angle))
{
/* angle in degree converted to radian */
let radians = angle * (Math.PI / 180);
return radians;
}
else
{
alert("Angle wasn't entered in numbers");
}
}
let theRadians =
convertDegreeToRadian(getAngleInDegree());
function sineOfAngle()
{
let sine = Math.sin(theRadians).toFixed(2);
return sine;
}
console.log(sineOfAngle());
alert(sineOfAngle());
}());
javascript:(
/* Trigonometry - Cosine */
function()
{
function getAngleInDegree()
{
let angle = parseFloat(prompt("Enter an
angle in degrees:"));
return angle;
}
function convertDegreeToRadian(angle)
{
if (!isNaN(angle))
{
/* angle in degree converted to radian */
let radians = angle * (Math.PI / 180);
return radians;
}
else
{
alert("Angle wasn't entered in numbers");
}
}
let theRadians =
convertDegreeToRadian(getAngleInDegree());
function cosineOfAngle()
{
let cosine =
Math.cos(theRadians).toFixed(2);
return cosine;
}
console.log(cosineOfAngle());
alert(cosineOfAngle());
}());
javascript:(
/* Trigonometry - Tangent */
function()
{
function getAngleInDegree()
{
let angle = parseFloat(prompt("Enter an
angle in degrees:"));
return angle;
}
function convertDegreeToRadian(angle)
{
if (!isNaN(angle))
{
/* angle in degree converted to radian */
let radians = angle * (Math.PI / 180);
return radians;
}
else
{
alert("Angle wasn't entered in numbers");
}
}
let theRadians =
convertDegreeToRadian(getAngleInDegree());
function tangentOfAngle()
{
let tangent =
Math.tan(theRadians).toFixed(2);
return tangent;
}
console.log(tangentOfAngle());
alert(tangentOfAngle());
}());
javascript:(
/* Trigonometry - Sine, Cosine, Tangent
Calculator */
function()
{
function calculateTrigonometry()
{
let angle = parseFloat(prompt("Enter an
angle in degrees:"));
if (!isNaN(angle))
{
let radians = angle * (Math.PI / 180);
let sine = Math.sin(radians);
let cosine = Math.cos(radians);
let tangent = Math.tan(radians);
alert(message);
}
else
{
alert("Angle wasn't entered in numbers");
}
}
calculateTrigonometry();
}());
javascript:(
/* Trigonometry - Circle made using Divs */
function()
{
function generateCircleOfDivs()
{
/* number of divs to create */
let numberOfDivs = 360;
let container =
document.createElement("div");
container.style.width = "200px";
container.style.height = "200px";
container.style.position = "fixed";
container.style.left = 100 + "px";
container.style.top = 100 + "px";
container.style.border = "1px solid black";
document.body.append(container);
/*----*/
let div = document.createElement("div");
div.style.width = "10px";
div.style.height = "10px";
div.style.background = "blue";
div.style.borderRadius = "50%";
div.style.position = "absolute";
div.style.left = xPos + "px";
div.style.top = yPos + "px";
container.append(div);
}
}
generateCircleOfDivs();
}());
javascript:(
/* Trigonometry - Spinning Circle of Divs */
function()
{
function generateCircleOfMovingDivs()
{
/* number of divs to create */
let numberOfDivs = 36;
/* center position */
let centerX = 100;
let centerY = 100;
let container =
document.createElement("div");
container.style.position = "fixed";
container.style.left = "20px";
container.style.top = "20px";
container.style.width = "200px";
container.style.height = "200px";
document.body.append(container);
}, 50);
}
}
generateCircleOfMovingDivs();
}());
javascript:(
/* Trigonometry - Pulsating Circle of Divs */
function()
{
function circleOfDivsPulsating()
{
/* number of divs to create */
let numberOfDivs = 60;
/* center position */
let centerX = 100;
let centerY = 100;
function animate()
{
if (growing)
{
scale += 0.01;
if (scale >= 2)
{
growing = false;
}
}
else
{
scale -= 0.01;
container.style.transform =
'scale('+scale+')';
}
setInterval(function()
{
animate();
}, 10);
}
circleOfDivsPulsating();
}());
javascript:(
/* Trigonometry - Draw Sine and Cosine */
function()
{
function graphSineAndCosine()
{
let canvas =
document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.left = 100 + "px";
canvas.style.top = 50 + "px";
canvas.width = 700;
canvas.height = 500;
/*----*/
context.lineTo(x, y);
}
context.strokeStyle = "blue";
context.lineWidth = 4;
context.stroke();
context.closePath();
context.lineTo(x, y);
}
context.strokeStyle = "red";
context.lineWidth = 4;
context.stroke();
context.closePath();
document.body.append(canvas);
}
graphSineAndCosine();
}());
/*
creates a dynamic trigonometric graph using
canvas to draw the sine and cosine functions
*/
javascript:(
/* Trigonometry - Sine Wave Motion */
function()
{
function generateSineWaveWithMotion()
{
let amplitude = 50;
let frequency = 0.1;
let xOffset = 0;
let yOffset = 100;
/*----*/
let canvas =
document.createElement('canvas');
canvas.style.position = 'fixed';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.zIndex = '10000';
canvas.style.pointerEvents = 'none';
document.body.append(canvas);
/*----*/
/*----*/
function drawSineWave()
{
context.clearRect(0, 0, canvas.width,
canvas.height);
context.beginPath();
for (let x = 0; x < canvasWidth; x += 1)
{
let y = amplitude * Math.sin(frequency *
x + xOffset) + yOffset;
context.lineTo(x, y);
}
context.strokeStyle = 'blue';
context.lineWidth = 4;
context.stroke();
}
function animate()
{
xOffset += 1;
drawSineWave();
requestAnimationFrame(animate);
}
animate();
}
generateSineWaveWithMotion();
}());
javascript:(
/* Trigonometry - Cosine Wave Motion */
function()
{
function generateCosineWaveWithMotion()
{
let amplitude = 50;
let frequency = 0.05;
let xOffset = 0;
let yOffset = 100;
/*----*/
let canvas =
document.createElement('canvas');
canvas.style.position = 'fixed';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.zIndex = '10000';
canvas.style.pointerEvents = 'none';
document.body.append(canvas);
/*----*/
/*----*/
function drawCosineWaves()
{
context.clearRect(0, 0, canvas.width,
canvas.height);
/*----*/
function animate()
{
xOffset += 0.1;
drawCosineWaves();
requestAnimationFrame(animate);
}
animate();
}
generateCosineWaveWithMotion();
}());
javascript:(
/* Trigonometry - Tangent Wave Motion */
function()
{
function generateTangentWaveWithMotion()
{
let amplitude = 50;
let frequency = 0.05;
let xOffset = 0;
let yOffset = 100;
/*----*/
let canvas =
document.createElement('canvas');
canvas.style.position = 'fixed';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.zIndex = '10000';
canvas.style.pointerEvents = 'none';
document.body.append(canvas);
/*----*/
/*----*/
function drawTangentWave()
{
context.clearRect(0, 0, canvas.width,
canvas.height);
context.beginPath();
for (let x = 0; x < canvasWidth; x += 1)
{
let y = amplitude * Math.tan(frequency *
x + xOffset) + yOffset;
context.lineTo(x, y);
}
context.strokeStyle = 'green';
context.lineWidth = 2;
context.stroke();
}
function animate()
{
xOffset += 0.1;
drawTangentWave();
requestAnimationFrame(animate);
}
animate();
}
generateTangentWaveWithMotion();
}());
javascript:(
/* Trigonometry - Sine and Cosine Wave Motion
*/
function()
{
function
generateSineAndCosineWavesWithMotion()
{
let amplitude = 50;
let frequency = 0.05;
let xOffset = 0;
let yOffset = 100;
/*----*/
let canvas =
document.createElement('canvas');
canvas.style.position = 'fixed';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.zIndex = '10000';
canvas.style.pointerEvents = 'none';
document.body.append(canvas);
/*----*/
/*----*/
function drawSineCosineWaves()
{
context.clearRect(0, 0, canvas.width,
canvas.height);
context.stroke();
context.stroke();
}
/*----*/
function animate()
{
xOffset += 0.1;
drawSineCosineWaves();
requestAnimationFrame(animate);
}
animate();
}
generateSineAndCosineWavesWithMotion();
}());
javascript:(
/* Trigonometry - Draw a Circle - Draw a 45
Degree Line - Create a Label */
function()
{
function drawCircleWith45DegreeLine()
{
let canvasWidth = 400;
let canvasHeight = 400;
let canvas =
document.createElement('canvas');
canvas.style.position = 'fixed';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.zIndex = '10000';
canvas.style.pointerEvents = 'none';
document.body.append(canvas);
/*----*/
/*----*/
function drawCircle()
{
let centerX = canvasWidth / 2;
let centerY = canvasHeight / 2;
context.strokeStyle = 'aqua';
context.lineWidth = 4;
context.stroke();
/*----*/
/*----*/
drawCircleWith45DegreeLine();
}());
/*
creates a circle with a 45 degree line and a label
*/
javascript:(
/* Trigonometry - Angle between two objects
Constant Updates */
function()
{
let object1 = document.createElement("div");
object1.style.position = "absolute";
object1.style.top = "50px";
object1.style.left = "50px";
object1.style.width = "20px";
object1.style.height = "20px";
object1.style.background = "red";
document.body.append(object1);
/*----*/
function calculateAngle()
{
let deltaX = object2.offsetLeft -
object1.offsetLeft;
return angle;
}
function updateAngleDisplay()
{
let angle = calculateAngle();
function moveObjectDown()
{
let top = parseInt(object2.style.top) || 0;
function animate()
{
moveObjectDown();
requestAnimationFrame(animate);
}
animate();
}());
javascript:(
/* Make Roads like in Cities Skylines */
function()
{
function makeRoad()
{
let road = document.createElement("div");
road.style.position = "absolute";
road.style.backgroundColor = "gray";
road.style.height = "20px";
road.style.width = "5px";
road.style.pointerEvents = "none";
document.body.append(road);
document.addEventListener("mousedown",
function(e)
{
isDrawing = true;
road.style.left = e.pageX + "px";
road.style.top = e.pageY + "px";
});
document.addEventListener("mouseup",
function()
{
isDrawing = false;
});
document.addEventListener("mousemove",
function(e)
{
if (isDrawing)
{
let currentX = e.pageX;
let currentY = e.pageY;
makeRoad();
}());
/*
After we have activated this bookmarklet, we
hold left click and drag our mouse to make the
road, and then let go of the left click to place the
road at that angle.
return password;
}
const generatedPassword =
generatePassword(parsedLength);
console.log("Password is " +
generatedPassword);
alert("Password is " +
generatedPassword);
}
}
makePassword();
}());
javascript:(
/* Password Generator - Specify How Many
Characters with Input Validation */
function()
{
function makePassword()
{
function generatePassword(whichAmount)
{
const characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM
NOPQRSTUVWXYZ0123456789!@#$%^&*()_-
+=<>?/{}[]";
return password;
}
if (!isNaN(parsedLength) &&
parsedLength > 0)
{
const generatedPassword =
generatePassword(parsedLength);
console.log("Password is " +
generatedPassword);
alert("Password is " +
generatedPassword);
}
else
{
alert("You didn't enter how many
characters you want the password to be.");
}
}
}
makePassword();
}());
javascript:(
/* Robot AI - Array of Objects - Responds once to
EXACT word(s) */
function()
{
const responses =
[
{
keyword: "hi",
response: "Howdy! Good to see you bud"
},
{
keyword: "how is the weather today",
response: "Very Nice!"
},
{
keyword: "how are you",
response: "I'm doing good, you?"
},
{
keyword: "bye",
response: "Bye. Talk to you soon"
}
];
function createRobot()
{
const userInput = prompt("Ask me a
question:");
if (userInput)
{
const responseObj =
responses.find(function (obj)
{
return obj.keyword.toLowerCase() ===
userInput.toLowerCase();
});
if (responseObj)
{
alert(responseObj.response);
}
else
{
alert("Rephrase the question");
}
}
}
createRobot();
}());
javascript:(
/* Robot AI - Array of Objects - Responds to
EXACT word(s) Continuously */
function()
{
const responses =
[
{
keyword: "hi",
response: "Howdy! Good to see you,
bud"
},
{
keyword: "how is the weather",
response: "Very nice!"
},
{
keyword: "how are you",
response: "I'm doing good, you?"
},
{
keyword: "bye",
response: "Bye. Talk to you soon"
}
];
function createRobot()
{
while (true)
{
const userInput = prompt("Ask me a
question:");
if (!userInput)
{
/* exit the loop if the user cancels or
enters nothing */
break;
}
const responseObj =
responses.find(function (obj)
{
return obj.keyword.toLowerCase() ===
userInput.toLowerCase();
});
if (responseObj)
{
alert(responseObj.response);
}
else
{
alert("Rephrase the question");
}
}
}
createRobot();
}());
javascript:(
/* Robot AI - Array Of Objects - Responds to
word(s) continuously with language
comprehension (keyword-based) */
function()
{
const responses =
[
{
keyword: "hi",
response: "Howdy! Good to see you,
bud"
},
{
keyword: "weather",
response: "Very nice!"
},
{
keyword: "how are you",
response: "I'm doing good, you?"
},
{
keyword: "bye",
response: "Bye. Talk to you soon"
}
];
function createRobot()
{
while (true)
{
const userInput = prompt("Ask me a
question:");
if (!userInput)
{
/* exit loop if user cancels or enters
nothing */
break;
}
if (responseObj)
{
alert(responseObj.response);
createRobot();
}());
javascript:(
/* Robot AI - Array Of Objects - Responds to
word(s) continuously with Language
Comprehension (keyword-based) and
Contextual Responses */
function()
{
function createRobot()
{
const responses =
[
{
keyword: "hi",
response: "Howdy bud"
},
{
keyword: "weather",
response: "Very nice!"
},
{
keyword: "how are you",
response: "I'm doing good, you?"
},
{
keyword: "bye",
response: "Bye. Talk to you soon"
}
];
while (true)
{
const userInput = prompt("Ask me a
question:");
if (!userInput)
{
/* exit loop if user cancels or enters
nothing */
break;
}
if (responseObj)
{
/* check for context and provide
contextual response */
if (context === responseObj.keyword)
{
if (context === "weather")
{
alert("Weather is still nice.");
}
else if (context === "how are you")
{
alert("Always Excellent");
}
else if (context === "hi")
{
alert("Hi again.");
}
}
else
{
alert(responseObj.response);
}
createRobot();
}());
javascript:(
/* Robot AI - Array Of Objects - Language
Comprehension (keyword-based), Contextual
Responses and Random Responses for when no
keywords are found */
function()
{
const responses =
[
{
keyword: "hi",
response: "Howdy bud"
},
{
keyword: "weather",
response: "Very nice!"
},
{
keyword: "how are you",
response: "I'm doing good, you?"
},
{
keyword: "bye",
response: "Bye. Talk to you soon"
}
];
const randomResponses =
[
"That's interesting!",
"Would you tell me more?",
"Hmm, tell me more about that.",
"Would you elaborate?",
"Interesting, please go on.",
"Fascinating! Tell me more.",
];
function createRobot()
{
/* initialize context variable */
let context = null;
function getRandomResponse()
{
const randomIndex =
Math.floor(Math.random() *
randomResponses.length);
return randomResponses[randomIndex];
}
while (true)
{
const userInput = prompt("Ask me a
question:");
if (!userInput)
{
/* exit loop if user cancels or enters
nothing */
break;
}
if (responseObj)
{
/* check for context and provide
contextual response */
if (context === responseObj.keyword)
{
if (context === "weather")
{
alert("Weather is still nice.");
}
else if (context === "how are you")
{
alert("Always Excellent");
}
else if (context === "hi")
{
alert("Hi again.");
}
}
else
{
alert(responseObj.response);
}
createRobot();
}());
javascript:(
/* Robot AI - Array Of Objects - Language
Comprehension (keyword-based), Contextual
Responses, Random Responses and
Calculations */
function()
{
const responses =
[
{
keyword: "hi",
response: "Howdy bud"
},
{
keyword: "weather",
response: "It's a beautiful day outside!"
},
{
keyword: "how are you",
response: "I'm doing good, you?"
},
{
keyword: "bye",
response: "Bye. Talk to you soon."
},
{
keyword: "interests",
response: "Computer Science is fun."
}
];
const randomResponses =
[
"That's interesting!",
"Would you tell me more?",
"Hmm, tell me more about that.",
"Would you elaborate?",
"Interesting, please go on.",
"Fascinating! Tell me more.",
];
function createRobot()
{
/* initialize context variable */
let context = null;
function getRandomResponse()
{
const randomIndex =
Math.floor(Math.random() *
randomResponses.length);
return randomResponses[randomIndex];
}
while (true)
{
const userInput = prompt("Ask me a
question:");
if (!userInput)
{
/* exit loop if user cancels or enters nothing */
break;
}
if (responseObj)
{
/* check for context and provide
contextual response */
if (context === responseObj.keyword)
{
if (context === "weather")
{
alert("Weather is still nice.");
}
else if (context === "how are you")
{
alert("Always excellent.");
}
else if (context === "hi")
{
alert("Hi again.");
}
}
else
{
alert(responseObj.response);
}
/*----*/
else
{
/* check if user input is a calculation */
const result = calculate(userInput);
function calculate(input)
{
try
{
return eval(input);
}
catch(error)
{
/* invalid calculation */
return null;
}
}
createRobot();
}());
function createRobot()
{
let context = null;
while (true)
{
const userInput = prompt("Ask me a
question:");
if (!userInput)
{
break;
}
let responseObj =
responses.find(function(obj)
{
return
userInput.toLowerCase().includes(obj.keyword);
});
/* if keyword is found */
if (responseObj)
{
const randomIndex =
Math.floor(Math.random() *
responseObj.responses.length);
alert(responseObj.responses[randomIndex]);
context = responseObj.keyword;
}
else
{
const result = calculate(userInput);
function calculate(input)
{
try
{
return eval(input);
}
catch (error)
{
return null;
}
}
createRobot();
}());
javascript:(
/* Robot AI - Random Responses every time to
keywords and phrases and variations of
keywords and phrases found. Other random
response when no keywords are found - and
Calculations */
function()
{
/* if keyword is found, use these responses */
let responses =
[
{
keywords: ["hi", "howdy", "hey"],
responses: ["Howdy", "Hi there", "Hi"]
},
{
keywords: ["weather", "forecast",
"sunny", "cloudy"],
responses: ["It's a beautiful day.", "The
weather is very nice.", "It's sunny and warm."]
},
{
keywords: ["how are you", "what's up",
"what are you up to?"],
responses: ["I'm doing good, you?",
"Having fun and you?", "I'm good, how about
you?"]
},
{
keywords: ["bye", "goodbye", "take
care"],
responses: ["Bye. Talk to you soon.",
"Goodbye!", "Have fun."]
},
{
keywords: ["interests", "career"],
responses: ["Computer Science is fun.",
"Programming is lots of fun.", "I like
programming a lot."]
}
];
function createRobot()
{
let context = null;
while (true)
{
let userInput = prompt("Ask me a
question:");
if (!userInput)
{
break;
}
let responseObj =
responses.find(function(obj)
{
return
obj.keywords.some(function(keyword) {
return
userInput.toLowerCase().indexOf(keyword) !== -
1;
});
});
/* if keyword is found */
if (responseObj)
{
let randomIndex =
Math.floor(Math.random() *
responseObj.responses.length);
alert(responseObj.responses[randomIndex]);
if
(responseObj.keywords.indexOf("bye") !== -1)
{
break;
}
context = responseObj.keywords;
}
else
{
let result = calculate(userInput);
if (result !== null)
{
alert("The result is: " + result);
}
else
{
let randomIndex =
Math.floor(Math.random() *
randomResponses.length);
alert(randomResponses[randomIndex]);
}
}
}
}
function calculate(input)
{
try
{
return eval(input);
}
catch (error)
{
return null;
}
}
createRobot();
}());
javascript:(
/* Robot AI - Textbox for Input with Send Button -
Random Responses every time to keywords and
phrases and variations of keywords and phrases
found. Other random response when no
keywords are found - and Calculations*/
function()
{
let mainDiv = document.createElement("div");
mainDiv.style.position = "fixed";
mainDiv.style.top = "0";
mainDiv.style.right = "0";
mainDiv.style.padding = "5px";
mainDiv.style.backgroundColor = "rgb(0, 0,
0)";
mainDiv.style.color = "rgb(255, 255, 255)";
mainDiv.style.zIndex = "10000";
document.body.append(mainDiv);
let userInput =
document.createElement("input");
userInput.type = "text";
userInput.placeholder = "Type Words Here";
userInput.style.width = "200px";
userInput.style.paddingLeft = "10px";
userInput.style.paddingRight = "10px";
userInput.style.paddingTop = "4px";
userInput.style.paddingBottom = "4px";
mainDiv.append(userInput);
let sendButton =
document.createElement("button");
sendButton.textContent = "Send";
mainDiv.append(sendButton);
if (userQuestion)
{
let responseObj =
responses.find(function(obj)
{
return obj.keywords.some(function
(keyword)
{
return
userQuestion.toLowerCase().indexOf(keyword) !
== -1;
});
});
if (responseObj)
{
let randomIndex =
Math.floor(Math.random() *
responseObj.responses.length);
alert(responseObj.responses[randomIndex]);
if
(responseObj.keywords.indexOf("bye") !== -1)
{
context = null;
}
else
{
context = responseObj.keywords;
}
}
else
{
let result = calculate(userQuestion);
if (result !== null)
{
alert("The result is: " + result);
}
else
{
let randomIndex =
Math.floor(Math.random() *
randomResponses.length);
alert(randomResponses[randomIndex]);
}
}
userInput.value = "";
}
};
function calculate(input)
{
try
{
return eval(input);
}
catch (error)
{
return null;
}
}
}());
/* and diagram */
off
A B
on
A B
/* or diagram */
off
on
B
/* and or diagram */
A C
off
B D
A C
on
B D
True Artificial Intelligence System
16-Gon
Tautology
MI 1111 CI
1101 1011
AND XNOR
0001 1001
LP RP
0011 0101
OR NOR
0111 1000
RC LC
1010 1100
XOR NAND
0110 1110
CNI MNI
Contra-
0100 0010
-diction
0000
For More Tutorials:
CollegeOfScripting.weebly.com
CollegeOfScripting.wordpress.com
GitHub.com/ChristopherTopalian
Youtube.com/ScriptingCollege
Twitter.com/CollegeOfScript
sites.google.com/view/CollegeOfScripting
Dedicated to God the Father
This book is created by the
College of Scripting Music & Science
Always remember, that each time you write a
script with a pencil and paper, it becomes
imprinted so deeply in memory that the
material and methods are learned extremely
well. When you Type the scripts, the same is
true. The more you type and write out the
scripts by keyboard or pencil and paper, the
more you will learn programming!
Write and Type EVERY example that you find.
Keep all of your scripts organized.
Every script that you create increases your
programming abilities.
SEEING CODE, is one thing,
but WRITING CODE is another.
Write it, Type it, Speak It, See It, Dream It.
CollegeOfScripting.weebly.com