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">{"playlist":[{"type":"object","name":"sample","artists":"sample"}]}</td>
                </tr>
            </tbody>
        </table>

    </body>
</html>
Classroom JSON Data
{"playlist":[{"type":"object","name":"sample","artists":"sample"}]}

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("Playlist object");

class Song {
  constructor(name, artist) {
    this.name = name;
    this.artist = artist;
  }

  getJSON() {
    const obj = { type: typeof this, name: this.name, artist: this.artist };
    const json = JSON.stringify(obj);
    return json;
  }

  logIt() {
    console.info(this);
    element.append("Song JSON: <br>");
    element.append(this.getJSON() + "<br>");
  }
}

class Playlist {
  constructor(songs) {
    this.songs = songs;
  }

  getJSON() {
    const songArray = this.songs.map(song => song.getJSON());
    const jsonString = JSON.stringify({ playlist: songArray });
    return jsonString.replace(/\\+/g, '');
  }

  logIt() {
    console.info(this);
    element.append("Playlist JSON: <br>");
    element.append(this.getJSON() + "<br>");
  }
}

function constructPlaylist() {
  const songs = [
    new Song("Shake It Off", ["Taylor Swift, Max Martin, Shellback"]),
    new Song("Getaway Car", "Taylor Swift, Jack Antonoff"),
    new Song("Boys Don't Cry", "Robert Smith, Lol Tolhurst, Michael Dempsey")
  ];

  return new Playlist(songs);
}

const playlist = constructPlaylist();
playlist.logIt();
$('#jsonText').text(playlist.getJSON());

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 playlist = JSON.parse(jsonText).classroom;
console.log(playlist);

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

    <script>
        $(document).ready(function() {
            fetch('https://playourshiny.duckdns.org/songdatabase', { mode: 'cors' })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('API response failed');
                    }
                    return response.json();
                })
                .then(data => {
                    for (const row of data) {
                        // Append each row to the table body
                        $('#flaskBody').append('<tr><td>' +
                            row.id + '</td><td>' +
                            row.title + '</td><td>' +
                            row.artist + '</td></tr>');
                    }
                    // Initialize DataTable after adding all rows
                    $("#flaskTable").DataTable();
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        });
    </script>
</body>
</html>
%%html
<html>
<head>
  <title>Playlist Table</title>
  <style>
    table {
      border-collapse: collapse;
      width: 100%;
    }

    th, td {
      padding: 8px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }

    th {
      background-color: #f2f2f2;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <table id="playlistTable">
    <thead>
      <tr>
        <th>Name</th>
        <th>Artist</th>
      </tr>
    </thead>
    <tbody id="playlistBody">
      <!-- Table rows will be dynamically generated here -->
    </tbody>
  </table>

  <div id="jsonText"></div>

  <script>
    console.log("Playlist object");

    class Song {
      constructor(name, artist) {
        this.name = name;
        this.artist = artist;
      }

      getJSON() {
        const obj = { type: typeof this, name: this.name, artist: this.artist };
        const json = JSON.stringify(obj);
        return json;
      }

      logIt() {
        console.info(this);
        element.append("Song JSON: <br>");
        element.append(this.getJSON() + "<br>");
      }
    }

    class Playlist {
      constructor(songs) {
        this.songs = songs;
      }

      getJSON() {
        const songArray = this.songs.map(song => song.getJSON());
        const jsonString = JSON.stringify({ playlist: songArray });
        return jsonString.replace(/\\+/g, '');
      }

      logIt() {
        console.info(this);
        element.append("Playlist JSON: <br>");
        element.append(this.getJSON() + "<br>");
      }
    }

    function constructPlaylist() {
      const songs = [
        new Song("Shake It Off", ["Taylor Swift, Max Martin, Shellback"]),
        new Song("Getaway Car", "Taylor Swift, Jack Antonoff"),
        new Song("Boys Don't Cry", "Robert Smith, Lol Tolhurst, Michael Dempsey")
      ];

      return new Playlist(songs);
    }

    const playlist = constructPlaylist();

    // Generating the HTML table
    const playlistTable = $("#playlistTable");
    const playlistBody = $("#playlistBody");

    playlist.songs.forEach(song => {
      const row = $("<tr></tr>");
      const nameCell = $("<td></td>").text(song.name);
      const artistCell = $("<td></td>").text(Array.isArray(song.artist) ? song.artist.join(", ") : song.artist);

      row.append(nameCell);
      row.append(artistCell);
      playlistBody.append(row);
    });

    // Displaying playlist JSON
    const jsonText = $("#jsonText");
    jsonText.text("Playlist JSON: \n" + playlist.getJSON());
  </script>
</body>
</html>
Playlist Table
Name Artist

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
  • Consider what you need to work on to be stronger developer
  • Show something creative or unique, no cloning
  • Be ready to talk to Teacher for 5 to 10 minutes. Individually!!!
  • Show in Jupyter Notebook during discussion, show Theme and ChatGPT
  • Have a runtime final in GithHub Pages (or Fastpage)
%%js
console.log("Playlist object");

class Song {
  constructor(name, artist) {
    this.name = name;
    this.artist = artist;
  }

  getJSON() {
    const obj = { type: typeof this, name: this.name, artist: this.artist };
    const json = JSON.stringify(obj);
    return json;
  }

  logIt() {
    console.info(this);
    element.append("Song JSON: <br>");
    element.append(this.getJSON() + "<br>");
  }
}

class Playlist {
  constructor(songs) {
    this.songs = songs;
  }

  getJSON() {
    const songArray = this.songs.map(song => song.getJSON());
    const jsonString = JSON.stringify({ playlist: songArray });
    return jsonString.replace(/\\+/g, '');
  }

  logIt() {
    console.info(this);
    element.append("Playlist JSON: <br>");
    element.append(this.getJSON() + "<br>");
  }
}

function constructPlaylist() {
  const songs = [
    new Song("Shake It Off", ["Taylor Swift, Max Martin, Shellback"]),
    new Song("Getaway Car", "Taylor Swift, Jack Antonoff"),
    new Song("Boys Don't Cry", "Robert Smith, Lol Tolhurst, Michael Dempsey")
  ];

  return new Playlist(songs);
}

const playlist = constructPlaylist();
playlist.logIt();
$('#jsonText').text(playlist.getJSON());
%%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 playlist = JSON.parse(jsonText).playlist;
console.log(playlist);

// from classroom object creates rows and columns in HTML table
element.append("<br>Formatted data sample from jsonText <br>");
for (var row of playlist) {
    element.append(row.name + " " + row.artist + '<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.artist + '</td>')
    // tr to end row
    $('#classroom').append('</tr>');
}
%%html
<html>
<head>
    <!-- load jQuery and DataTables styles and scripts -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
</head>
<body>
    <table id="flaskTable" class="table" style="width:100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Artist</th>
            </tr>
        </thead>
        <tbody id="flaskBody"></tbody>
    </table>

    <script>
        $(document).ready(function() {
            fetch('https://playourshiny.duckdns.org/songdatabase', { mode: 'cors' })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('API response failed');
                    }
                    return response.json();
                })
                .then(data => {
                    for (let i = 0; i < 20; i++) { // Iterate only for the first 20 rows
                        const row = data[i];
                        if (!row) {
                            break; // Stop the loop if there are fewer than 20 rows
                        }
                        // Append each row to the table body
                        $('#flaskBody').append('<tr><td>' +
                            row.id + '</td><td>' +
                            row.title + '</td><td>' +
                            row.artist + '</td></tr>');
                    }
                    // Initialize DataTable after adding all rows
                    $("#flaskTable").DataTable();
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        });
    </script>
</body>
</html>
ID Title Artist
%%js
<html>
<body>
<form id="uinput" action="#">
  Enter the artist you want to find: <input type="text" name="artist"
  id="artist"><br>
  Enter the song: <input type="text" name="song" id="song"><br>
  <input type=button onclick="songCheck()" value="Submit">
</form>
</body>

<p id="out"></p>

<p>Songs!</p>

<table>
  <thead>
  <tr>
    <th>Song</th>
    <th>Artists</th>
  </tr>
  </thead>
  <tbody id="results">
    <!-- javascript generated data -->
  </tbody>
</table>



<script>
//sets variables and connects userinput through id
const table = document.getElementById('results');
const songIn = document.getElementById('song');
const artistIn = document.getElementById('artist');
const outputElement = document.querySelector('#out');

//creates function, which is activated by user clicking submit
function songCheck() {

    //changes user input to all lowercase (var allows for redefinition unlike const)
    var artistl = artistIn.value.toLowerCase();
    var songl = songIn.value.toLowerCase();

    //loops through rows in entire database table
    for (var i = 0; i < table.rows.length; i++) {
        const row = table.rows[i];

        //loops through all cells in the table
        for (var j = 0; j < row.cells.length; j++) {
            const cell = row.cells[j];

            //determines where the product is in the table
            if (cell.innerText.toLowerCase().includes(songl)) {
                //outputs where product is present in console (for error management)
                console.log(`song found in row ${i}`);
                var rowIndex = i;
                var prodrow = table.rows[rowIndex];
                //defines row and column of product, so it can be looped through to find string of allergy
                var specrow = document.querySelector(`#results tr:nth-child(${i+1})`);
                var speccells = specrow.querySelectorAll("td");

                //loop through specific row and column
                for (var k = 1; k < speccells.length; k++) {
                    const prodcell = prodrow.cells[k];
                    console.log(speccells[k].innerText.toLowerCase());
                    console.log(artistl);
                    //if this cell includes string inputted by user, output of where safe or not is returned in html
                    if (speccells[k].innerText.toLowerCase().includes(artistl)) {
                        console.log('This song contains the artist you are looking for!');
                        outputElement.textContent = 'This song contains the artist you are looking for!';
                        return;
                    } else {
                        console.log('This song does not contains the artist you are looking for:(');
                        outputElement.textContent = 'This song does not contains the artist you are looking for:(';
                        return;
                    }
                }
            //will inform user if product is not in table/database yet
            } else {
                console.log('Song is not in our database. Check spelling, or enter different song.');
                outputElement.textContent = 'Song is not in our database. Check spelling, or enter different song.';
            }
        }
    }
}
            
</script>
</script>
%%html
<html>
<head>
    <!-- load jQuery and DataTables styles and scripts -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
</head>
<body>
    <div>
        <label for="song">Enter the song:</label>
        <input type="text" id="song">
    </div>
    <div>
        <label for="artist">Enter the artist you want to find:</label>
        <input type="text" id="artist">
    </div>
    <button onclick="songCheck()">Submit</button>
    <p id="out"></p>
    <table id="flaskTable" class="table" style="width:100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Artist</th>
            </tr>
        </thead>
        <tbody id="flaskBody"></tbody>
    </table>

    <script>
        const table = document.getElementById('flaskTable');
        const songIn = document.getElementById('song');
        const artistIn = document.getElementById('artist');
        const outputElement = document.getElementById('out');

        function songCheck() {
            const artistl = artistIn.value.toLowerCase();
            const songl = songIn.value.toLowerCase();

            for (let i = 0; i < table.rows.length; i++) {
                const row = table.rows[i];

                for (let j = 0; j < row.cells.length; j++) {
                    const cell = row.cells[j];

                    if (cell.innerText.toLowerCase().includes(songl)) {
                        console.log(`Song found in row ${i}`);
                        const rowIndex = i;
                        const prodrow = table.rows[rowIndex];
                        const specrow = document.querySelector(`#flaskTable tr:nth-child(${i+1})`);
                        const speccells = specrow.querySelectorAll("td");

                        for (let k = 1; k < speccells.length; k++) {
                            const prodcell = prodrow.cells[k];
                            console.log(speccells[k].innerText.toLowerCase());
                            console.log(artistl);

                            if (speccells[k].innerText.toLowerCase().includes(artistl)) {
                                console.log('This song contains the artist you are looking for!');
                                outputElement.textContent = 'This song contains the artist you are looking for!';
                                return;
                            } else {
                                console.log('This song does not contain the artist you are looking for:(');
                                outputElement.textContent = 'This song does not contain the artist you are looking for:(';
                                return;
                            }
                        }
                    } else {
                        console.log('Song is not in our database. Check spelling or enter a different song.');
                        outputElement.textContent = 'Song is not in our database. Check spelling or enter a different song.';
                    }
                }
            }
        }

        $(document).ready(function() {
            fetch('https://playourshiny.duckdns.org/songdatabase', { mode: 'cors' })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('API response failed');
                    }
                    return response.json();
                })
                .then(data => {
                    for (let i = 0; i < 20; i++) {
                        const row = data[i];
                        if (!row) {
                            break;
                        }
                        $('#flaskBody').append('<tr><td>' +
                            row.id + '</td><td>' +
                            row.title + '</td><td>' +
                            row.artist + '</td></tr>');
                    }
                    $("#flaskTable").DataTable();
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        });
    </script>
</body>
</html>

ID Title Artist