JavaScript Tutorial
Quick launch into Variables, Functions, Arrays, Classes, HTML.
- chat
- response generated by ChatGPT in 7 seconds at 5/29/2023 8:00:00 PM
- Hacks
- Output Explored
- Multiple Outputs using One Variable
- Building a Person Object and JSON
- Project Usage: JavaScript Sorting
- CSA Goals & Programming Goals
response generated by ChatGPT in 7 seconds at 5/29/2023 8:00:00 PM
Certainly! Here's a simple JavaScript program that will greet you with "Hi!" when executed:
console.log("Hi!");
You can run this code in any JavaScript environment, such as a web browser console or a Node.js environment, and it will output "Hi!" to the console. If you want to personalize the greeting by using your name, you can modify the code as follows:
const name = "Your Name";
console.log("Hi, " + name + "!");
Replace "Your Name" with your actual name, and when you run the program, it will greet you with "Hi, Your Name!" in the console.
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)
%%html
<html>
<head>
<style>
{
background-color: #42e3f5;
padding: 8px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="output">
Testing.
</div>
</body>
</html>
%%js // required to allow cell to be JavaScript enabled
element.append("Hi there.");
// Browser Console output; debugging or tracing
element.append(" I am talking to Mr. Mortensen right now.");
element.append(" I am taking AP CSA next year.");
%%js
console.log("Multiple Outputs Using One Variable");
var msg = "I am defining the variable msg here.";
// 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);
%%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>
</head>
<body>
<table id="jsonTable">
<thead>
<tr>
<th>NBA PLAYER JSON Data</th>
</tr>
</thead>
<tbody>
<tr>
<td id="jsonText">{
"player": [
{
"name": "LeBron James",
"team": "Los Angeles Lakers",
"ppg": 28,
},
{
"name": "Steph Curry",
"team": "Golden State Warriors",
"ppg": 30,
},
]
}
</td>
</tr>
</tbody>
</table>
</body>
</html>
%%js
class NBA {
constructor(name, team, ppg) {
this.name = name;
this.team = team;
this.ppg = ppg;
}
getJSON() {
const obj = {
name: this.name,
team: this.team,
ppg: this.ppg,
};
const json = JSON.stringify(obj);
return json;
}
logIt() {
console.info(this);
element.append(this.getJSON());
}
}
const NBAData = {
name: "LeBron James",
team: "Los Angeles Lakers",
ppg: 28,
};
const js = new NBA(
NBAData.name,
NBAData.team,
NBAData.ppg
);
js.logIt();
%%html
# defines the tableID that is going to be referred to in the future
<table id="sportsTable">
<thead>
<tr>
# these are the sortTable functions for each of the columns. the onclick allows for on click of the table header.
<th onclick="sortTable('assists per game')">Assists Per Game</th>
<th onclick="sortTable('minutes per game')">Minutes Per Game</th>
<th onclick="sortTable('blocks per game')">Blocks Per Game</th>
<th onclick="sortTable('defensive rebounds')">Defensive Rebounds</th>
<th onclick="sortTable('fg percent')">FG Percent</th>
<th onclick="sortTable('ft percent')">FT Percent</th>
<th onclick="sortTable('games played')">Games Played</th>
<th onclick="sortTable('height (inches)')">Height (inches)</th>
<th onclick="sortTable('name')">Name</th>
<th onclick="sortTable('offensive rebounds')">Offensive Rebounds</th>
<th onclick="sortTable('points per game')">Points Per Game</th>
<th onclick="sortTable('steals per game')">Steals Per Game</th>
<th onclick="sortTable('team')">Team</th>
<th onclick="sortTable('three percent')">Three Percent</th>
<th onclick="sortTable('weight (pounds)')">Weight (pounds)</th>
</tr>
</thead>
<tbody>
# sample data following on frontend, just for demo.
<tr>
<td>2</td>
<td>35</td>
<td>1</td>
<td>5</td>
<td>44</td>
<td>88</td>
<td>1421</td>
<td>81</td>
<td>LeBron James</td>
<td>6</td>
<td>28</td>
<td>1</td>
<td>Los Angeles Lakers</td>
<td>24</td>
<td>250</td>
</tr>
<tr>
<td>3</td>
<td>32</td>
<td>2</td>
<td>6</td>
<td>55</td>
<td>92</td>
<td>1231</td>
<td>75</td>
<td>Steph Curry</td>
<td>5</td>
<td>29</td>
<td>1</td>
<td>Golden State Warriors</td>
<td>34</td>
<td>185</td>
</tr>
</table>
<script>
// sortTable function meant to sort based on each column header.
function getColumnIndex(columnName) {
// each column name is taken in columnName to get its index.
const table = document.getElementById('sportsTable');
const headerRow = table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[0];
// contains the column headers, index 0
const headers = Array.from(headerRow.getElementsByTagName('th'));
return headers.findIndex(header => header.innerText.toLowerCase() === columnName.toLowerCase()) + 1;
// converts column header names to lowercase to account for sortTable definitions
}
function sortTable(columnName) {
const table = document.getElementById('sportsTable');
// constant calls the tableID that was previously defined
const rows = Array.from(table.tBodies[0].getElementsByTagName('tr'));
const headerRow = table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[0];
const isAscending = !headerRow.classList.contains('asc');
// this is a very important line - the asc class helps the function decide whether or not the column is going to be sorted in increasing order or decreasing order.
rows.sort((rowA, rowB) => {
let cellA = rowA.querySelector(`td:nth-child(${getColumnIndex(columnName)})`).innerText;
let cellB = rowB.querySelector(`td:nth-child(${getColumnIndex(columnName)})`).innerText;
// the nth-child selector is different from normal JS arrays, these have an index starting at 1 rather than 0
// the rows are sorted based on the column. getColumnIndex is used to get the index of the column.
if (columnName.toLowerCase() === 'name' || columnName.toLowerCase() === 'team') {
return isAscending ? cellA.localeCompare(cellB, undefined, { sensitivity: 'base' }) : cellB.localeCompare(cellA, undefined, { sensitivity: 'base' });
}
// these were for special situations. the name and team columns were not sorting properly, so the localeCompare was used to sort the rows alphabetically.
// Convert the cell values to numbers for the "Games Played" column
if (columnName.toLowerCase() === 'games played') {
cellA = parseInt(cellA);
cellB = parseInt(cellB);
}
// games played was not sorting for some odd reason, which is why this if statement was added.
// purpose is to parse the values as an integer and then sort numerically.
return isAscending ? cellA - cellB : cellB - cellA;
});
rows.forEach(row => table.tBodies[0].appendChild(row));
headerRow.classList.toggle('asc');
// this is meant for after sorting. after the sorting is done, the appendChild is meant to append these cell values back into the specified table.
}
</script>