Today
- Keyboard events
- Data storage
- Final Project
Recap from last class
- Adding and removing DOM nodes
- Keyboard events
Keyboard events
- To get text entered by your user, we usually rely on button clicks
(e.g., “Submit”)
- Button click indicates user is done with text entering
- Then, we can extract the text
<input type="text" name="module" id="module">
<button id="btn_add">Add a module!</button>
const addModule = (event) => {
const input = document.querySelector('input');
const moduleName = input.value;
};
However,
some use cases require handling keyboard events directly (e.g., games,
shortcuts)
Keyboard events
- Key is pressed — keydown
event
- Key is released — keyup
event
target.addEventListener("keydown", (event) => {
/* Key pressed */
});
target.addEventListener("keyup", (event) => {
/* Key released */
});
Keyboard events
key: value of the key pressed
ctrlKey: was Ctrl key active?
shiftKey: was Shift key active?
metaKey: was the meta key active?
Keyboard events
window.addEventListener("keydown", event => {
if (event.key == "v") {
document.body.style.background = "violet";
}
});
window.addEventListener("keyup", event => {
if (event.key == "v") {
document.body.style.background = "";
}
});
“Page turns violet when you hold the V key”
Which element is the event
listener?
window.addEventListener("keydown", event => {
if (event.key == "v") {
document.body.style.background = "violet";
}
});
window.addEventListener("keyup", event => {
if (event.key == "v") {
document.body.style.background = "";
}
});
window contains
the DOM document
![]()
window makes items globally available (functions, event
handlers, objects)
Today
- Keyboard events
- Data storage
- Final Project
Todo
- Open Activity
18
- The balloon should:
- Inflate 20% when ⬆️ is pressed
- Deflate 20% when ⬇️ is pressed
Hints
- What does the console show when ⬆️ and ⬇️ is pressed?
style.fontSize will change font for a given element
- Remember to include the unit (e..g,
px,
rem, em)
Today
- Keyboard events
- Data storage
- Final Project
Data storage
Client side storage
- JS enables data storage in users’ machines
- Cookies
- Web Storage
- IndexedDB
Client side storage
We will focus on Web
Storage in this class
Cookies
- Web Storage
IndexedDB
Web Storage
- Storing data for different origins (e.g., hostname)
- You can’t access data for other origins
- There is a limit
- Around 5 MiB of local storage per origin
Web Storage
Use cases
- Saving preferences (e.g., color scheme, font size)
- Previous site activity (e.g., shopping cart, login info)
- Saving documents for offline use
Web Storage
sessionStorage
- Persists data for as long as the browser is open
- Data is lost when browser is closed
localStorage
- Persists data even
after the browser is closed
Saving data in
localStorage
setItem(key, value)
- Save a data item
- Both
key and value must be strings
localStorage.setItem("bgcolor", "red");
localStorage.setItem("font", "Helvetica");
localStorage.setItem("image", "myCat.png");
Getting data from
localStorage
getItem(key)
- Return the string data for a given key
null, if the key doesn’t exist
const currentColor = localStorage.getItem("bgcolor");
const currentFont = localStorage.getItem("font");
const currentImage = localStorage.getItem("image");
Removing data from
localStorage
removeItem(key)
- Deletes the data item for a given key
localStorage.removeItem("image");
Todo
Adding data item to local
storage
- Open Activity
19 in Chrome/Firefox
- Go to Dev Tools –> Console
localStorage.setItem("button_label", "Add a module!");
localStorage.setItem("name", "YOUR NAME");
sessionStorage.setItem("session_key_1", "Session Value 1");
sessionStorage.setItem("session_key_2", "Session Value 2");
Todo
- Go to:
- Firefox: Dev Tools –> Storage
- Chrome: Dev Tools –> Application –> Storage
- Do you see the stored values?
Todo
- Restart the browser and reopen
index.html
- Go to:
- Firefox: Dev Tools –> Storage
- Chrome: Dev Tools –> Application –> Storage
- Which values persisted?
Todo
- Open Activity
19 in VS Code
- Copy the url and open it in Firefox/Chrome
- Go to:
- Firefox: Dev Tools –> Storage
- Chrome: Dev Tools –> Application –> Storage
- Do you see the stored values?
Web Storage
- Storing data for different origins (e.g., hostname)
- You can’t access data for other origins
How can we
store non-string data in localStorage?
We will use JSON
JSON
Structured data as a string
- Standard text-based format (string)
- Follows JavaScript object syntax
JSON
{
"orderId": "12345",
"customer": {
"firstName": "Jane",
"lastName": "Doe",
"address": "123 Main St"
},
"items": [
{
"product": "Laptop",
"quantity": 1,
"price": 1200.50
}
]
}
Converting between objects
and text
JSON.parse
- String –> JS Object (or value)
JSON.stringify
- JS Object (or value) –> String
JSON.parse
String –> JS Object (or
value)
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// Expected output: 42
console.log(obj.result);
// Expected output: true
JSON.parse
String –> JS Object (or
value)
JSON.parse('[1, 5, "false"]');
What’s the outcome?
Todo
- Open Dev Tools –> Console
- Fix the error here:
JSON.parse("[1, 2, 3, 4, ]");
JSON.stringify
JS Object (or value) –>
String
console.log(JSON.stringify({ x: 5, y: 6 }));
// Expected output: '{"x":5,"y":6}'
const a = ["foo", "bar"];
JSON.stringify(a);
// '["foo","bar"]'
How can we
store non-string data in localStorage?
We will use JSON
Saving session
const session = {
screens: [],
state: true,
};
session.screens.push({ name: "screenA", width: 450, height: 250 });
// Converting the JSON string with JSON.stringify()
// then saving with localStorage in the name of session
localStorage.setItem("session", JSON.stringify(session));
Restoring saved
session from localStorage
const restoredSession = JSON.parse(
localStorage.getItem("session"));
Today
- Keyboard events
- Data storage
- Final Project
Final project — 2
presentations & 3 submissions
- Proposal submission: 5 points
- Proposal Presentation: 8 points
- Final presentation: 10 point
- Code and documentation: 20 point
- Mandatory group review: 2 points
Final project — 2
presentations & 3 submissions
- Proposal submission: 5 points
- Proposal Presentation: 8 points
- Final presentation: 10 point
- Code and documentation: 20
point
- Mandatory group review: 2 points
Grading rubric
for final submission (see syllabus)
- The app must be installable using Chrome — 1.5
points
- The app (and the browser version) should work for different devices
— 4.5 points
- At least 3 non-trivial pages with user interaction support —
3 points
Grading
rubric for final submission (see syllabus) — contd.
- Stores and retrieves persistent data — 3
points
- Includes icon and consistent theme — 3 points
- Ensures accessibility — 3 points
- Documentation for the code and the system — 2
points
Bonus Features (maximum 5
points)
5 non-trivial pages or more — 1 point
Use of camera — 1.5 points
Use of microphone — 1.5 points
Use of location — 2 points
Integrates user facing
generative AI features — 3 points
Final Project
- Considerable flexibility in terms of topic
- develop a chatbot interface?
- redesign an existing app (e.g., Penn State Go app, Apple
Music)?
Final project topic
- Focus on your portfolio
- Showcasing it in your job/internship applications?
- Maybe prototype for broader reach?
Next todos: Check Canvas
What questions do you have?
We
will work on final project during our class from next week
- Thursday (10/23): Selecting topics and sketching UI/user-flow
- Tuesday (10/28): Proposal and presentation
We will take attendance
on those days
Mandatory group review
- Due at the end of the class
- Report evaluating performance of each group member (including
yourself)
- Will also be used to adjust project
grades
- Be fair, courteous, and respectful to your group
member