JavaScript and Jupyter references

JavaScript is the most important language you need to learn as a frontend developer. Jupyter Notebooks is a convenient way to learn the language without the overhead of creating a full Website. Jupyter Notebooks had ChatGPT plugins to assist with design and troubleshooting problems. This Notebook has colors on HTML pages that were designed with a dark mode background.

output using HTML and CSS

Multiple cells are used to setup HTML in this lesson. Many of the JavaScript cells will use the output tag(s) to write into the HTML that has been setup.

  • %%html is used to setup HTML code block
  • "style" tag enables visuals customization
  • "div" tag is setup to receive data
%%html
<html>
    <head>
        <style>
            #output {
                background-color: #353b45;
                padding: 10px;
                border: 3px solid #ccc;
            }
        </style>
    </head>
    <body>
        <div id="output">
            Hello!
        </div>
    </body>
</html>
Hello!

output explored

There are several ways to ouput the classic introduction message: "Hello, World!"

  • Before you go further, open Console on your Browser. JavaScript developer leaves Console open all the time!!!
  • The function console.log() outputs to Console, this is often used for inspection or debugging.
  • "Hello, World" is a String literal. This is the referred to as Static text, as it does not change. Developer call this a hard coded string.
  • "Hello, World" literal is a parameter to console.log(), element.txt() and alert().
  • The element.txt function is part of Jupyter Notebook %%js magic. This is convenient for Notebook and testing.
  • The alert command outputs the parameter to a dialog box, so you can see it in this Jupyter notebook. The alert commands are shown, but are commented out as the stop run all execution of the notebook.
  • Note, in a Web Application Debugging: An alert is often used for less savy Developers. Console is used by more savy developers; console often requires setting up a lot of outputs. Source level debugging is the most powerful solution for debugging and does not require alert or console commands.
%%js // required to allow cell to be JavaScript enabled
console.log("JavaScript/Jupyter Output Intro");

// Browser Console output; debugging or tracing
console.log("Hello, World!");
console.log("Hello, World Again!");

// Document Object Model (DOM) output; output to HTML, CSS which is standard for a Web Page
// <mark>select element method</mark>: DOM native JavaScript get, document.getElementByID
document.getElementById("output").textContent = "Hello, World!";
// <mark>jQuery CSS-style method</mark>: Tag for DOM selector, $('#output')
$('#output').append('<br><b>Hello World Again!');  // br is break or new line, b is bold

// Jupyter built in magic element for testing and convenience of development
element.text("Hello, World!"); // element is output option as part of %%js magic
element.append('<br><b>Hello World Again!');

//alert("Hello, World!");

multiple outputs using one variable

This second example is a new sequence of code, two or more lines of code forms a sequence. This example defines a variable, thank goodness!!! In the previous example we were typing the string "Hello, World" over and over. Observe with the variable msg="Hello, World!"; we type the string once and now use msg over and over.

  • The variable "var msg =" is used to capture the data
  • The console.log(msg) outputs to console, be sure to Inspect it!
  • The element.text() is part of Jupyter Notebooks and displays as output blow the code on this page. Until we build up some more interesting data for Web Site, we will not use be using the Python HTML, CSS technique.
  • The alert(msg) works the same as previous, but as the other commands uses msg as parameter.
%%js
console.log("Variable Definition");

var msg = "Hello, World!";

// Use msg to output code to Console and Jupyter Notebook
console.log(msg);  //right click browser select Inspect, then select Console to view
element.text(msg);
//alert(msg);

output showing use of a function

This example passes the defined variable "msg" to the newly defined "function logIt(output)".

  • There are multiple steps in this code..
    • The "definition of the function": "function logIt(output) {}" and everything between curly braces is the definitions of the function. Passing a parameter is required when you call this function.
    • The "call to the function:"logIt(msg)" is the call to the function, this actually runs the function. The variable "msg" is used a parameter when calling the logIt function.
  • Showing reuse of function...
    • There are two calls to the logIt function
    • This is called Prodedural Abstraction, a term that means reusing the same code
%%js
console.log("Function Definition");

/* Function: logIt
 * Parameter: output
 * Description: The parameter is "output" to console and jupyter page
*/
function logIt(output) {
    console.log(output); 
    element.append(output + "<br>");
    //alert(output);
}

// First sequence calling logIt function
var msg = "Hello, World!";
logIt(msg);

// Second sequence calling logIt function
var msg = "Hello, <b>Students</b>!" // replaces content of variable
var classOf = "Welcome CS class of 2023-2024."
logIt(msg + "  " + classOf); // concatenation of strings

output showing Loosely typed data

JavaScript is a loosely typed language, meaning you don't have to specify what type of information will be stored in a variable in advance.

  • To define a variable you prefix the name with var or const. The variable type is determined by JavaScript at runtime.
  • Python and many interpretive languages are loosely typed like JavaScript. This is considered programmer friendly.
  • Java which is a compiled language is strongly typed, thus you will see terms like String, Integer, Double, and Object in the source code.
  • In JavaScript, the typeof keyword returns the type of the variable. Become familiar with type as it is valuable in conversation and knowing type help you understand how to modify data. Each variable type will have built in methods to manage content within the data type.
%%js
console.log("Examine Data Types");

// Function to add typeof to output
function getType(output) {
    return typeof output + ": " + output;
}

// Function defintion
function logIt(output) {
    console.log(getType(output));  // logs string
    console.info(output);          // logs object
    element.append(getType(output) + "<br>");  // adds to Jupyter output
    //alert(getType(output));
}

// Common Types
element.append("Common Types <br>");
logIt("Mr M"); // String
logIt(1997);    // Number
logIt(true);    // Boolean
element.append("<br>");

// Object Type, this definition is often called a array or list
element.append("Object Type, array <br>");
var scores = [
    90,
    80, 
    100
];  
logIt(scores);
element.append("<br>");

// Complex Object, this definition is often called hash, map, hashmap, or dictionary
element.append("Object Type, hash or dictionary <br>");
var person = { // key:value pairs seperated by comma
    "name": "Mr M", 
    "role": "Teacher"
}; 
logIt(person);
logIt(JSON.stringify(person));  //method used to convert this object into readable format

Build a Person object and JSON

JavaScript and other languages have special properties and syntax to store and represent data. In fact, a class in JavaScript is a special function.

  • Definition of class allows for a collection of data, the "class Person" allows programmer to retain name, github id, and class of a Person.
  • Instance of a class, the "const teacher = new Person("Mr M", "jm1021", 1977)" makes an object "teacher" which is an object representation of "class Person".
  • Setting and Getting properties After creating teacher and student objects, observe that properties can be changed/muted or extracted/accessed.
%%html
<!-- load jQuery and tablesorter scripts -->
<html>
    <head>
        <!-- load jQuery and tablesorter scripts -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
        <style>
            /* CSS-style selector maps to table id or other id's in HTML */
            #jsonTable, #flaskTable {
                background-color: #353b45;
                padding: 10px;
                border: 3px solid #ccc;
                box-shadow: 0.8em 0.4em 0.4em grey;
            }
        </style>
    </head>

    <body>
        <!-- Table for writing and extracting jsonText -->
        <table id="jsonTable">
            <thead>
                <tr>
                    <th>Classroom JSON Data</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td id="jsonText">{"classroom":[{"type":"object","name":"sample","ghID":"sample","classOf":2000,"role":"sample"}]}</td>
                </tr>
            </tbody>
        </table>

    </body>
</html>
Classroom JSON Data
{"classroom":[{"type":"object","name":"sample","ghID":"sample","classOf":2000,"role":"sample"}]}
%%js
console.log("Person objects");

/* 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: role uses a default property, 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);
    //Log to Jupter
    element.append("Person object in JSON <br>");
    element.append(this.getJSON() + "<br>");  
    //alert(this.getJSON());
  }
    
}

// make a new Person Object
const teacher = new Person("Mr M", "jm1021", 1977); // object type is easy to work with in JavaScript
// update role to Teacher
teacher.setRole("Teacher"); // set the role
teacher.logIt();  // log to console

// make a new Person Object
const student = new Person("Jane Doe", "jane", 2007); // object type is easy to work with in JavaScript
student.logIt(); // log to console

Build a Classroom Array/List of Persons and JSON

Many key elements are shown again. New elements include...

  • Building an Array, "var students" is an array of many persons
  • Building a Classroom, this show forEach iteration through an array and .push adding to an array. These are key concepts in all programming languages.
%%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);
    //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);
    
    //Classroom json
    element.append("Classroom object in JSON<br>");
    element.append(this.json + "<br>");  
    //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("Anthony", "tonyhieu", 2022),
        new Person("Bria", "B-G101", 2023),
        new Person("Allie", "xiaoa0", 2023),
        new Person("Tigran", "Tigran7", 2023),
        new Person("Rebecca", "Rebecca-123", 2023),
        new Person("Vidhi", "VidhiKulkarni", 2024)
    ];

    // 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();
// enable sharing of data across jupyter cells
$('#jsonText').text(compsci.json);  // posts/embeds/writes compsci.json to HTML DOM element called jsonText

for loop to generate Table Rows in HTML output

This code extracts JSON text from HTML, that was placed in DOM in an earlier JavaScript cell, then it parses text into a JavaScript object. In addition, there is a for loop that iterates over the extracted object generating formated rows and columns in an HTML table.

  • Table generation is broken into parts...
    • table data is obtained from a classroom array inside of the extracted object.
    • the JavaScript for loop allows the construction of a new row of data for each Person hash object inside of the the Array.
    • in the loop a table row <tr> ... </tr> is created for each Hash object in the Array.
    • in the loop table data, a table column, <td> ... </td> is created for name, ghID, classOf, and role within the Hash object.
%%js
console.log("Classroom Web Page");

// extract JSON text from HTML page
const jsonText = document.getElementById("jsonText").innerHTML;
console.log(jsonText);
element.append("Raw jsonText element embedded in HTML<br>");
element.append( jsonText + "<br>");

// convert JSON text to Object
const classroom = JSON.parse(jsonText).classroom;
console.log(classroom);

// from classroom object creates rows and columns in HTML table
element.append("<br>Formatted data sample from jsonText <br>");
for (var row of classroom) {
    element.append(row.ghID + " " + row.name + '<br>');
    // tr for each row, a new line
    $('#classroom').append('<tr>')
    // td for each column of data
    $('#classroom').append('<td>' + row.name + '</td>')
    $('#classroom').append('<td>' + row.ghID + '</td>')
    $('#classroom').append('<td>' + row.classOf + '</td>')
    $('#classroom').append('<td>' + row.role + '</td>')
    // tr to end row
    $('#classroom').append('</tr>');
}
%%html
<head>
    <!-- load jQuery and DataTables syle and scripts -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
    <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
</head>
<table id="flaskTable" class="table" style="width:100%">
    <thead id="flaskHead">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>DOB</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody id="flaskBody"></tbody>
</table>

<script>
  $(document).ready(function() {
    fetch('https://flask.nighthawkcodingsociety.com/api/users/', { mode: 'cors' })
    .then(response => {
      if (!response.ok) {
        throw new Error('API response failed');
      }
      return response.json();
    })
    .then(data => {
      for (const row of data) {
        // BUG warning/resolution - DataTable requires row to be single append
        $('#flaskBody').append('<tr><td>' + 
            row.id + '</td><td>' + 
            row.name + '</td><td>' + 
            row.dob + '</td><td>' + 
            row.age + '</td></tr>');
      }
      // BUG warning - Jupyter does not show Datatable controls, works on deployed GitHub pages
      $("#flaskTable").DataTable();
    })
    .catch(error => {
      console.error('Error:', error);
    });
  });
</script>
ID Name DOB Age

Hacks

One key to these hacks is to build confidence with me going into final grade, I would like to see each student adapt this frontend work in their final project. Second key is the finished work can serve as review for the course, notes for the future in relationship to frontend.

  • Adapt this tutorial to your own work

As of Now, my Trimester 3 team is using a lot of JavaScript Code for the Final Night at the Museum project. Currently, we are using Javascript code to code a multiplayer game that allows the user to move a character in a game of red light green light. We are using Phaser, which is an additional javascript library that is used to make the framework for a game. It uses a lot of different sets of tools, functions, and components than traditional javascript code, but it does have similarities to this tutorial. While they have different functionality, the red light green light game utilizes classes. The classes for phaser are normally used to built apond other phaser attributes like events or physics. However, they work similarly because of their purpose to handle objects and their data to different functions.

  • Consider what you need to work on to be stronger developer
  • Show something creative or unique, no cloning show Theme and ChatGPT
  • Have a runtime final in GithHub Pages (or Fastpage)
%%html
<html lang="en">
    <head>
        <style> 
           input[type='Image'] { position: absolute; } /* positioning the images and formatting them as inputs */   /*help from Ryan Haki*/
        </style>   
     </head>
     
     <body>
     
        <p id="timer"></p> <!-- display time --> <!-- idea from Ryan Haki -->
        <p id="score"></p> <!-- display score --> <!-- idea from Ryan Haki -->
     <!--  set to an image  id         image  size                     points    call scoreboard_sp to update user's score  -->
        <input type="Image" id="test1" src="" height="150" width="150" points="" onclick="scoreboard_sp(1)" /> <!-- help from Ryan Haki -->
        <input type="Image" id="test2" src="" height="150" width="150" points="" onclick="scoreboard_sp(2)" /> <!-- help from Ryan Haki -->
        <input type="Image" id="test3" src="" height="150" width="150" points="" onclick="scoreboard_sp(3)" /> <!-- help from Ryan Haki -->
        <input type="Image" id="test4" src="" height="150" width="150" points="" onclick="scoreboard_sp(4)" /> <!-- help from Ryan Haki -->
        <input type="Image" id="test5" src="" height="150" width="150" points="" onclick="scoreboard_sp(5)" /> <!-- help from Ryan Haki -->
        <script>
         // array with the food items
         const foodimages = [
         {//image 1
            "id": 1, 
            "image": "https://png.pngtree.com/png-vector/20190130/ourlarge/pngtree-cute-minimalist-creative-cartoon-hamburger-png-image_611163.jpg", // image from pngtree.com
            "name": "Burger", 
            "points": "10"
         }, 
         {//image 2
            "id": 2, 
            "image": "https://thumbs.dreamstime.com/b/french-fries-cartoon-clipart-red-paper-box-carton-121897301.jpg", // image from dreamstime.com
            "name": "Fries", 
            "points": "20"
         },
         {//image 3
            "id": 3, 
            "image": "https://clipartix.com/wp-content/uploads/2016/04/Popcorn-kernel-clipart-free-clipart-images.png", // image from clipartix.com
            "name": "Popcorn", 
            "points": "30"
         },
         {//image 4
            "id": 4, 
            "image": "http://clipart-library.com/images/rTjGjMqec.png", // image from clipart-library.com
            "name": "Hotdog", 
            "points": "40"
         },
         {//image 5
            "id": 5, 
            "image": "http://clipart-library.com/img/1144032.png", // image from clipart-library.com
            "name": "icecream", 
            "points": "50"
         }];
         console.log(foodimages); // display foodimages and its objects in the console to check if the data is correct
   
         // each use of 'document.getElementById' was suggested by one of my team members, Ryan Haki. I used 'document.getElementById' a lot in this program so I am going to give credit in this comment so that I don't need to credit him for each time I used it.
   
         function get_images() {
            // set image to a test in order to be moved across the screen in a later part of the program( function onscreen(){} )
            document.getElementById("test1").src = foodimages[0].image;
            document.getElementById("test2").src = foodimages[1].image;
            document.getElementById("test3").src = foodimages[2].image;
            document.getElementById("test4").src = foodimages[3].image;
            document.getElementById("test5").src = foodimages[4].image;
            // set points to a test in order to be pulled to update the score in a later part of the program( function scoreboard_sp(idid){} )
            document.getElementById("test1").points = parseInt(foodimages[0].points);
            document.getElementById("test2").points = parseInt(foodimages[1].points);
            document.getElementById("test3").points = parseInt(foodimages[2].points);
            document.getElementById("test4").points = parseInt(foodimages[3].points);
            document.getElementById("test5").points = parseInt(foodimages[4].points);
         }
   
         var score = 0; // set the starting score to 0 points
         document.getElementById("score").innerHTML = "Score: " + score + " points" // display that the starting score is 0 points
         function scoreboard_sp(idid) { // updates the score based on what food has been clicked
            if (idid == 1) {
               points = document.getElementById("test1").points; // gets the point value of food1
            } else if (idid == 2) {
               points = document.getElementById("test2").points; // gets the point value of food2
            } else if (idid == 3) {
               points = document.getElementById("test3").points; // gets the point value of food3
            } else if (idid == 4) {
               points = document.getElementById("test4").points; // gets the point value of food4
            } else if (idid == 5) {
               points = document.getElementById("test5").points; // gets the point value of food5
            } else { // what happens when the user doesn't click on a food
               points = 0;
            }
            score = score + points; // updates the score to add the amount of points from the food that was clicked
            console.log(score);
            document.getElementById("score").innerHTML = "Score: " + score + " points" // displays the score after it has been updated
         }
   
         function moveimage(idid) {
            var test = document.getElementById(idid);
         test.style.top = Math.floor((Math.random() * 500) + 1) + "px"; // moves each image to a random spot from top to buttom
         test.style.left = Math.floor((Math.random() * 1200) + 1) + "px"; // moves each image to a random spot from left to right
         test.style.visibility = 'visible'; // displays the image
         }
         
         function clearimage(idid) {
            var clear1 = document.getElementById(idid)
            clear1.style.visibility = 'hidden'; // hides the image
         }
   
         function clearimages() { //hides all images
            clearimage("test1");
            clearimage("test2");
            clearimage("test3");
            clearimage("test4");
            clearimage("test5");
         }
         
         function stop_moveimage(moveimage_interval) { // stops the game
            clearInterval(moveimage_interval); //stops moving the images 
            clearimages(); //hides all images
         }
   
         timer = 30 // starting time set to 30 seconds
         document.getElementById("timer").innerHTML = "Time left: " + timer + " seconds" // displays starting time
   
         function onscreen() {
            clearimages(); // hides all images
            something = Math.ceil(Math.random() * 5); // determines how many images will appear at a time
            timer = timer - 1 // decreases time by 1
            document.getElementById("timer").innerHTML = "Time left: " + timer + " seconds" // displays the updated time
            if (something >= 1) {
            moveimage("test1"); // displays food1 and puts it in a random spot on the screen
            } 
            if (something >= 2) {
            moveimage("test2"); // displays food1-2 and puts them in random spots on the screen
            }
            if (something >= 3) {
            moveimage("test3"); // displays food1-3 and puts them in random spots on the screen
            }
            if (something >= 4) {
            moveimage("test4"); // displays food1-4 and puts them in random spots on the screen
            }
            if (something >= 5) {
            moveimage("test5"); // displays food1-5 and puts them in random spots on the screen
            }
         }
   
         get_images(); // calls get_images()
         thing = setInterval(onscreen, 1000); //runs the function onscreen each second
         image_timeout = setTimeout(stop_moveimage, 30000, thing); // ends the game after 30 seconds
   
      </script>
   </body>

</div> </div> </div> </div> </div> </div>