Planning and Emoji Notebook | Frontend Hacks | SASS Hacks | Brazil Guide | Italy Guide |
Frontend Hacks
Data Types, DOM, JavaScript, Input, Output, and Debugging Hacks
Hacks Below
- HTML(see index.md)
- Data Types
- DOM
- JavaScript
- Input
- Output
- Debugging
Data Types Hacks
%%js
console.log("Object: assigning key-value objects");
var obj_risha = {
name: "Risha",
age: 15,
grade: 10,
classes: ["AP Chemistry", "AP World History", "Honors Principles of Engineering", "AP Computer Science Principles", "AP Calculus BC"],
interests: ["Cybersecurity", "piano", "biking"],
color_fav: ["green"],
food_fav: ["pasta"]
};
// print obj to the console
console.log(obj_risha);
// Changing favorite color from green to blue
console.log("Object: mutating the key color_fav from green to blue")
obj_risha.color_fav = "blue"
console.log(obj_risha);
console.log(obj_risha.color_fav);
// Calculating years until graduation
console.log("Object: calculating # of years until graduation from grade key")
let yearstograduation = 12 - obj_risha.grade
console.log("Years until I graduate:", yearstograduation)
// Determining types of field:
console.log("Type of var grade:", typeof obj_risha.grade)
console.log("Type of var classes:", typeof obj_risha.classes)
console.log("Type of var color_fav:", typeof obj_risha.color_fav)
console.log("Type of var food_fav:", typeof obj_risha.food_fav)
<IPython.core.display.Javascript object>
DOM Hacks
%%html
<div style="background-color: #05034b;">
<a id="aboutLink" href="/risha_guha_2025_1/about/">
<button class="block"><b>About Page</b></button>
</a>
<p></p>
<a id="indexLink" href="/risha_guha_2025_1/">
<button class="block"><b>Index Page</b></button>
</a>
<p></p>
<p style="color: white;">Use the buttons above to navigate to important pages on this site.</p>
<p style="color: white;" id="switchedParagraph">Not Switched Yet!</p>
<!-- Switch button placed outside the links -->
<button class="block" id="switchLinks"><b>Switch!</b></button>
</div>
<script>
const aboutLink = document.getElementById("aboutLink");
const indexLink = document.getElementById("indexLink");
const switchedText = document.getElementById("switchedParagraph");
const switchButton = document.getElementById("switchLinks");
const switchLinks = () => {
// Swap the hrefs of the links
const aboutHref = aboutLink.href;
const indexHref = indexLink.href;
aboutLink.href = indexHref;
indexLink.href = aboutHref;
// Change the text of the paragraph
switchedText.textContent = "Switched!";
};
// Add an event listener to the "Switch!" button
switchButton.addEventListener("click", switchLinks);
</script>
Use the buttons above to navigate to important pages on this site.
Not Switched Yet!
</div>
A copy of this code is on the tools.md page to run.
JavaScript Hacks
%%js
let a = 2343;
let b = 393821;
if (a > b) {
console.log("a is greater");
} else if (b > a) {
console.log("b is greater");
} else {
console.log("both are equal");
}
// Perform arithmetic operations
let x = 10;
let y = 5;
let addition = x + y;
let subtraction = x - y;
let multiplication = x * y;
let division = x / y;
console.log("Addition:", addition);
console.log("Subtraction:", subtraction);
console.log("Multiplication:", multiplication);
console.log("Division:", division);
<IPython.core.display.Javascript object>
Input Hacks
%%html
<!-- Help Message -->
<h3>Input scores, press tab to add each new number.</h3>
<!-- Totals -->
<ul>
<li>
Total : <span id="total">0.0</span>
Count : <span id="count">0.0</span>
Average : <span id="average">0.0</span>
Grade: <span id="Grade">N/A</span>
</li>
</ul>
<!-- Rows added using scores ID -->
<div id="scores">
<!-- javascript generated inputs -->
</div>
<script>
// Executes on input event and calculates totals
function calculator(event) {
var key = event.key;
// Check if the pressed key is the "Tab" key (key code 9) or "Enter" key (key code 13)
if (key === "Tab" || key === "Enter") {
event.preventDefault(); // Prevent default behavior (tabbing to the next element)
var array = document.getElementsByName('score'); // setup array of scores
var total = 0; // running total
var count = 0; // count of input elements with valid values
for (var i = 0; i < array.length; i++) { // iterate through array
var value = array[i].value;
if (parseFloat(value)) {
var parsedValue = parseFloat(value);
total += parsedValue; // add to running total
count++;
}
}
// update totals
document.getElementById('total').innerHTML = total.toFixed(2); // show two decimals
document.getElementById('count').innerHTML = count;
if (count > 0) {
document.getElementById('average').innerHTML = (total / count).toFixed(2);
var average = parseFloat(document.getElementById('average').innerHTML);
var grade = "";
if (average >= 90) {
grade = "A";
} else if (average >= 80) {
grade = "B";
} else if (average >= 70) {
grade = "C";
} else if (average >= 60) {
grade = "D";
} else {
grade = "F";
}
document.getElementById('Grade').innerHTML
= grade;
} else {
document.getElementById('average').innerHTML = "0.0";
document.getElementById('Grade').innerHTML = "N/A";
}
} else {
document.getElementById('average').innerHTML = "0.0";
}
// adds newInputLine, only if all array values satisfy parseFloat
if (count === document.getElementsByName('score').length) {
newInputLine(count); // make a new input line
}
}
// Creates a new input box
function newInputLine(index) {
// Add a label for each score element
var title = document.createElement('label');
title.htmlFor = index;
title.innerHTML = index + ". ";
document.getElementById("scores").appendChild(title); // add to HTML
// Setup score element and attributes
var score = document.createElement("input"); // input element
score.id = index; // id of input element
score.onkeydown = calculator // Each key triggers event (using function as a value)
score.type = "number"; // Use text type to allow typing multiple characters
score.name = "score"; // name is used to group all "score" elements (array)
score.style.textAlign = "right";
score.style.width = "5em";
document.getElementById("scores").appendChild(score); // add to HTML
// Create and add blank line after input box
var br = document.createElement("br"); // line break element
document.getElementById("scores").appendChild(br); // add to HTML
// Set focus on the new input line
document.getElementById(index).focus();
}
// Creates 1st input box on Window load
newInputLine(0);
</script>
Input scores, press tab to add each new number.
- Total : 0.0 Count : 0.0 Average : 0.0 Grade: N/A
Output Hacks
%%js
console.log("Classroom object");
/* class: Person
* Description: A collection of Person data
*/
class Person {
/* method: constructor
* parameters: name, ghID - GitHub ID, classOf - Graduation Class
* description: returns object when "new Person()" is called with matching parameters
* assignment: this.name, this.ghID, ... are properties retained in the returned object
* default: this.role is a default property retained in object, it is set to "Student"
*/
constructor(name, ghID, classOf, role="Student") {
this.name = name;
this.ghID = ghID;
this.classOf = classOf;
this.role = role;
}
/* method: setter
* parameters: role - role in classroom
* description: this.role is updated from default value to value contained in role parameter
*/
setRole(role) {
this.role = role;
}
/* method: getter
* description: turns properties of object into JSON object
* return value: JSON object
*/
getJSON() {
const obj = {type: typeof this, name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};
const json = JSON.stringify(obj);
return json;
}
/* method: logIT
* description: this Person object is logged to console
*/
logIt() {
//Person Object
console.info(this);
// HTML output tag
document.getElementById("output").textContent = this.getJSON();
//Log to Jupter
element.append("Person json <br>");
element.append(this.getJSON() + "<br>");
//alert(this.getJSON());
}
}
/* class: Classroom
* Description: A collection of Person objects
*/
class Classroom {
/* method: constructor
* parameters: teacher - a Person object, students - an array of Person objects
* description: returns object when "new Classroom()" is called containing properties and methods of a Classroom
* assignment: this.classroom, this.teacher, ... are properties retained in the returned object
*/
constructor(teacher, students) {
/* spread: this.classroom contains Teacher object and all Student objects
* map: this.json contains of map of all persons to JSON
*/
this.teacher = teacher;
this.students = students;
this.classroom = [teacher, ...students]; // ... spread option
this.json = '{"classroom":[' + this.classroom.map(person => person.getJSON()) + ']}';
}
/* method: logIT
* description: this Classroom object is logged to console
*/
logIt() {
//Classroom object
console.log(this);
// HTML output
document.getElementById("data").textContent = this.json;
document.getElementById("output").textContent = this.json;
//Classroom json
element.append("Classroom object in JSON: ");
element.append(this.json);
//alert(this.json);
}
}
/* function: constructCompSciClassroom
* Description: Create data for Classroom and Person objects
* Returns: A Classroom Object
*/
function constructCompSciClassroom() {
// define a Teacher object
const teacher = new Person("Mr M", "jm1021", 1977, "Teacher"); // optional 4th parameter
// define a student Array of Person objects
const students = [
new Person("Risha", "blackstar3092", 2027),
new Person("Vibha", "vibha1019", 2027),
new Person("Ava", "ava-dn", 2025),
];
// make a CompSci classroom from formerly defined teacher and student objects
return new Classroom(teacher, students); // returns object
}
// assigns compsci to the object returned by "constructCompSciClassroom()" function
const compsci = constructCompSciClassroom();
// output of Objects and JSON in CompSci classroom
compsci.logIt();
console.log("Classroom Web Page");
// extract JSON text from output element in HTML page
const jsonText = document.getElementById("data").innerHTML;
// convert JSON text to a JavaScript Object to process
const classroom = JSON.parse(jsonText).classroom;
console.log(classroom);
// make an HTML Out format for pretty display
/* Template literals (`), can make HTML generation more concise;
* the map functions generates row strings and the join method combines them;
* this replaces longer and ugly for loop and string concatenation.
*/
const htmlOut = `
<table>
<thead>
<tr>
<th>Name</th>
<th>GitHub ID</th>
<th>Class Of</th>
<th>Role</th>
</tr>
</thead>
<tbody>
${classroom.map(row => `
<tr>
<td>${row.name}</td>
<td>${row.ghID}</td>
<td>${row.classOf}</td>
<td>${row.role}</td>
</tr>
`).join('')}
</tbody>
</table>
`;
// assign/set htmlOut to output element in HTML page
document.getElementById("output").innerHTML = htmlOut;
// show raw HTML
console.log(htmlOut);
element.append(htmlOut);
<IPython.core.display.Javascript object>
console.log()
helps users find errors in code by allowing you to inspect values, the flow of the code, and track down potential issues. It helps inspect variable issues, check code flow, debug function outputs, identify undefined or null values, catch errors in loops or conditional statements, and check the state of objects or arrays.
Debugging Hacks
%%js
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var alphabetList = [];
for (var i = 0; i < 10; i++) {
alphabetList.push(alphabet[i]);
}
console.log(alphabetList);
<IPython.core.display.Javascript object>
What I changed: I changed
alphabetList.push(i);
to alphabetList.push(alphabet[i]);
This allows me to actually call the alphabet variable when listing the first 10 letters; previously, it was only outputing the variable i
.
%%js
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var alphabetList = [];
for (var i = 0; i < 10; i++) {
alphabetList.push(alphabet[i]);
}
console.log(alphabetList);
//New Code Step below
let letterNumber = 5
for (var i = 0; i < alphabetList.length; i++) {
if (i === letterNumber - 1) {
console.log(alphabetList[i] + " is letter number " + (letterNumber) + " in the alphabet");
}
}
<IPython.core.display.Javascript object>
What I changed:
I changed
i === letterNumber
to i === letterNumber - 1
and letterNumber + " is letter number 1 in the alphabet"
to alphabetList[i] + " is letter number " + (letterNumber) + " in the alphabet"
This, once again, allows me to actually output the letter instead of just a number. Also, by subtracting a number from letterNumber, we account for the 0 number in all arrays/lists.
%%js
let odds = [];
let i = 1;
while (i <= 10) {
odds.push(i);
i += 2;
}
console.log(odds);
<IPython.core.display.Javascript object>
What I changed: I changed the starting value to 1 because otherwise, adding 2 to each value will always output even numbers. I also changed the function name to odds instead of evens for consistency.