---
# System prepended metadata

title: TINKER - Javascript Part I
tags: [' js', ' tinker', mstu5003]

---

---
tags: mstu5003, tinker, js
Group Members: 
---
# TINKER - Javascript Part I

:::success
Group Members: 
Yixiong Chen (yc2216), 
Justin Arenas (ja3688), 
Jiayi Xue (jx2517), 
Ingrid Wang (yw3744),
Dilys Han (dd3142)

Date: November 20, 2022

<span style="color:blue"><i>Note: All of our answers are noted in green.</i></span>
:::

See demonstration: https://codepen.io/jmk2142/pen/eGZRME

:::info
**README:**

At the bottom (after the tinker activities) there is a [**NOTES**](#NOTES) section with a text-based conceptual explanation of many of the things going on here. My recommendation:

- Play with the interface to get a sense of what it does.
- Look at the Tinker Tasks and code first to get a sense of the context.
- Read the NOTES as it will arm you with ideas to approach the tinker task/problems.
- Then try the tinker problems.
:::

## Tinker Tasks

This tinker takes the basics of what you learned about variables, functions, arrays, and puts it in a real context of web-pages. This is our first foray into actual user-computer interaction. As a general rule of thumb, at the very least, for every section/part you should be thinking:

> What is the STATE?

-- current functions/variables/innovated/been called/return anything? 
> What is the SEQUENCE?

-- how does the whole thing possibly goes? 
-- 
> What is the CAUSALITY?

In your groups - try to articulate these line by line, part by part. Articulation should be _out loud_ or _in writing_. It's very important that you do this outside of your head.


### Part 0 - Warmup - [Definitely Maybe](https://youtu.be/TDe1DqxwJoc)

> Jimmy asks, Sally... will you go to the prom with me?
> [Sally](https://youtu.be/cmpRLQZkTb8?t=1m10s) handwrites the following reply back.
```javascript=
function yes(x){
  return x();
}
function no(x){
  return 'yes';
}
function maybe(no){
  return no;
}
var definitely = maybe(yes(no));
```
**Inputs and Outputs** - Try to mentally solve the problem first (using pen and paper OKAY.) Then try it to see the actual answer. Then adjust your answer accordingly.
1. What do you think is the value of `definitely`?
  - Is Jimmy going to the prom with Sally?
2. - How does this work? (Code, not relationships.)
3.  When is the `no` function called?
4. On the line `var definitely = maybe(yes(no));` there aren't ()s immediately after `no`. What is the significance of this?
5.  Explain how this code snippet works, line by line, part by part.
  - Be very specific
  - Use important keywords
  - Provide explanation of what each syntax detail represents as well
:::success
**RESPONSE:** 
1. Since the value of definitely is a "yes," we believe Jimmy is going to the prom with Sally. 
2. From `function yes（no)` to `function (no)`,then to `function maybe(yes)`.
3. The `no` function is called after `function yes(no)`.
4. The significance of this is that this is a function that encapsulates other functions and the computer will read the most inward function first before it leads to the outer ones.
5. The input value is "no". Once "no" is input to the function yes(no), then it returns no(). After function no(x), "yes" is returned. After that, the output of function maybe(yes) turns out to be "yes".



:::
**Template Literals** - Backtick symbols `` ` `` in JS are different than single-quotes `'` and double-quotes`"`. They are used to make what is called, `template literals`.
```javascript
var x = "bitter";
var y = "sweet";
var z = `Coffee is ${x}, Sugar is ${y}, Monday mornings are ${x}${y}.`;
var n = "Coffee is " + x + ", Sugar is " + y + ", Monday mornings are " + x + y + ".";

// z and n end up being the same values after the String is resolved.
// "Coffee is bitter, Sugar is sweet, Monday mornings are bittersweet."
```
- What does the `${}` syntax represent?
:::success
**RESPONSE:**  ${ } (dollar sign curly bracket) is an example of a template literal. It is used to embed a variable, an array value, or an object property in a string. 
:::
- Why are template literals super useful for us?
::: success 
**RESPONSE:**  Template literals allow for multi-line string, string interpolation with embedded expressions and special constructs, meaning they allow the codes to be more readable and concise. 
:::


### Part 1

:::info
**Parts 1-4: Breaking it Apart**

It might help to start by forking the codepen into four separate pens. And for each pen, reducing/removing all unused code, i.e. both HTML and JS for that part, so that all that remains are the functional ones for that part to work. (There is a reason why I don't do this for you...)

Reducing what is visually in front of you can greatly help you to focus on the bits that are relevant to the sub-problem at hand.

Note that `printLog()` is utilized across multiple parts.
:::

- Click on the link at the top to view the `index-simple.html` version. Compare the HTML between this version and the Bootstrap version. Compare the JS between this version and the Bootstrap version.
  - How do these two versions compare with regard to helping you understand Javascript?
:::success
  **RESPONSE:**  The key difference is CSS style and functionalities. JavaScript is designed to manipulate web pages and it is used to create interactive functionality.  A webpage would still work without JavaScript, although to a lesser extent. JavaScript is what makes HTML and CSS animated and gives life to the webpage.
:::
- Play with the interface (each of the buttons) and observe how the program reacts. When tinkering, try changing the order in which you play with the interface. Take note of the printed _history_.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
    - Be sure to articulate both aspects of the HTML and JS.
::: success
**RESPONSE:**  At the beginning, the STATE of the user name is preset as unknown person. Once first name and last name are inputed, the variable printName will be changed to what we have inputed. The SEQUENCE of the inputs matters, it should be: "Set name" first, then "Greet User" and end with "Print Name". If we click "Greet User" before "Set Name", we will get "Hello wonderful walrus" in the pop-up window. The CAUSALITY is obvious. Once the user's first name and last name inputs, the name in the "Greet User" and "Print Name" will be changed to what we input.

:::
* What does the `prompt` function return?
:::success
**RESPONSE:**  The `prompt` function returns either a first name or a last name.
:::
*  Expain what you think the `document.querySelector()` does. Talk about this in terms of the functions vocabulary presented in the Notes.
:::success 
**RESPONSE:**  `document.querySelector()` returns the first element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

:::
* If I told you that `document.querySelector` RETURNS something, what do you think that something is?
:::success
**RESPONSE:** Select something within the brackets after it (the values that the users inputted or slected) or the default value
:::
* How could you alter the `printName` function in order to print the users first and last name in the browser window tab?
:::success
**RESPONSE:** For instance, we can change it to a function as shown below

 ````javascript
function printName() {
    var fullName = firstName + " " + lastName;
    document.querySelector('#fullName').textContent = fullName;
    printLog('#prePartOne', `printName called(): ${fullName}`);
    result = prompt(fullName);
}
 ````


:::
  - How would you use the `makeFullName` function to shorten the `greetUser` and `printName` code?
:::success
 ````javascript
function makeFullName() {
    let greet = greetUser.value;
    let print = printName.value;
    makeFullName.textContent = greet + " " + print;
} ````
:::

	


### Part 2

- Play with the interface (each of the buttons) and observe how the program reacts. When tinkering, try changing the order in which you play with the interface. Take note of the printed _history_.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.

:::success
**RESPONSE:**  
- State:  
originally: `username` = "no username" and `email` is undefined. 

- Sequence: 
   1)When the user typed username and moved away the cursor, `updateUsername` function is being triggered.
  *** `username`'s value is changed based on what the user has been typed in the username. 
   2) When the user typed email and moved away the cursor, `updateEmail` function is being triggered.
  *** `email`'s value is changed based on what the user has been typed in the email. 
   3) When the user click `Print Info`, `printInfo` function is being triggered. 
   4) When the user click `reset`, all of the context from username and email is being cleared.

- Causality: 
  1) When sequence 1 is being triggered, the "history" section will display the text relate with "updateUsername". 
  2) When sequence 2 is being triggered, the "history" section will display the text relate with "updateEmail".
  3) When sequence 3 is being triggered, the "history" section will display the text relate with "print email" and changed unknown user to the username that the user has been entered.
  4) When sequence 4 is being triggered, the "history" section, "username" and "email" sections will clear all texts.
:::

- Be sure to articulate both aspects of the HTML and JS.
    - What kind of events are happening in Part 2 and explain how this relates to when the handlers will run.

:::success
**RESPONSE:** 
   **Event 1**: After enter the `username` or `email` and if the state of `username` or `email` is changed, `updateEmail` function / `updateUsername` function will be triggered. The "hisotry" section will display texts (example is shown below): 
   ![](https://i.imgur.com/3szO952.png)

   **Event 2:** After click "Print Info", `printInfo` function is being triggered and the "History" section will appear text relates to "printInfo" and top "unknown person" portion changed as shown below: 
   ![](https://i.imgur.com/tvUDY3E.png)


   
   **Event** 3: When you click the "reset" button, `resetInfo` function is triggered. All the text from "hisotry" and "input" sections are cleared. The top part changed back to "unknown person" again. 
![](https://i.imgur.com/FS1w6o0.png)

:::

- What is `event.target`?
    
:::success
**RESPONSE:**  

 It accesses the `event` object's`target` property. 

:::
 
- What does the dot `.value, .textContent, .innerHTML` represent in this context?
:::success
**RESPONSE:**  
It's using dot notation (.) to read an context's property. 
`.value` of the context will affect the state of the context. 
Changing the `.textContent`will affect the context of the "username". Changing the `.innerHTML` will affect the HTML code for "#prePartTwo" web element. 
:::

- Why does `updateEmail` have a parameter for `event` data but the other functions do not?
:::success
**RESPONSE:**  
The parameter "banana" is a local variable for `updateEmail`. It is optional of whether have a the function has a local variable. 
:::

- `resetInfo` is actually a little broken. Why?
:::success
**RESPONSE:**  
After clicked the `reset` button, all of the content from the "hisotry" and "input" sections are cleared, however, if you click on `print info`, the previous print infor still appears. Example: 
![](https://i.imgur.com/c8RB7Me.png)

We can use the following code to fix the `resetInfo` function: 
```javascript=
username = "no username";
email = undefined;
```
:::


### Part 3

- Play with the interface (each of the buttons) and observe how the program reacts. Take note of the printed _INFO_.
  - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
    - Be sure to articulate both aspects of the HTML and JS.
:::success
**RESPONSE:**  
State in JS is an object that stores dynamic data of a component to follow changes between renderings. It changes based on user input. For HTML, the state shows the state stored in the state object.

Sequence in JS is a set of instructions executed one after the other. Sequence in HTML refers to the order of tags used in a document and there is only one sequnce, which is html tag, head tag, title tag and body tag. 
:::


- Compare and contrast the `showImageData` and `showImageViaParent` functions.
- How do these two different functions achieve the same output?

::: success
**RESPONSE:** 
They both have function called `printElementPartialData` and they both called the `querySelector` to choose the image. But they have different parameter of this function.
:::

  - Compare and contrast the `showParentData` and `showParentViaImage` functions.
    - How do these two different functions achieve the same output?
::: success
**RESPONSE:**  
`showParentData` returns the direct parent element of the selected element while `showParentViaImage` shows information on the parent via an image that is nested within the parent. 
:::





- Play with the Change Image button.
  - Can you modify the related code so that each time you pressed it, it would show 1 of 5 images, cycling through to the next image per click?
    - There are several ways to solve this.

::: success
**RESPONSE:**  
```
HTML:

<IMG SRC=" image URL of image 0" name="5 pictures">
<IMG SRC=" image URL of image 1" name="5 pictures">
<IMG SRC=" image URL of image 2" name="5 pictures">
<IMG SRC=" image URL of image 3" name="5 pictures">
<IMG SRC=" image URL of image 4" name="5 pictures">

CSS:
img[name=5 pictures]:hover
{
  cursor:pointer;
}

JS:
var img = new Array()
    img[0] = "image URL of image 0";
    img[1] = "image URL of image 1";
    img[2] = "image URL of image 2";
    img[3] = "image URL of image 3";
    img[4] = "image URL of image 4";

var imgNumber = 0

function NextImage()
{
imgNumber++
if (imgNumber == img.length)
    imgNumber = 0
document.images["5 pictures"].src = img[imgNumber]
}
```
:::


- Play with the Show This Button button.
  - What is the value of the property `onclick` of the button?
::: success
**RESPONSE:**  
  The value of the property of the button is the target (child) in the event (parent).
:::



### Part 4 - Challenge

- Play with the interface (each of the form inputs) and observe how the program reacts. Carefully take note of what actions cause what results, in what order. **ALSO**, open up your Chrome Devtools and watch your inspect elements tool pane as you interact with this form.

 - Explain how this program works with regard to STATE, SEQUENCE, and CAUSALITY of each line, and/or specific parts of a line as appropriate. Use specific vocabulary, as demonstrated in the notes section.
    - Be sure to articulate both aspects of the HTML and JS.
:::success
**RESPONSE:** 
This part is divided into two vertical sections: left and right. User interact with the interface in the left panel and result shown in real time at the right panel. There are four sections and two buttons in the left panel.
    
The <i>first section</i> is a form where user can choose from a predefined set of choices. In this section, there is not an interactive feature, so there is no function involved.

The <i>second section</i> is a checkbox item in which one can select one or more boxes at the same time. It is a standard checkbox form.
        
The <i>third section</i> is a radio choice, which is a standard radio class with coffee chosen as the default value

The <i>fourth section</i> is an input area. We have the following three functions here:

- The onkeypress event calls for the function `saveCoffee(event)`, meaning that once a key a press, the function is called

- The onkeyup event calls for the function `characterTyped(event)`, meaning that once the key is not long press the function is called

- The onblur event calls for the function `editingOff()`, meaning that once mouse is moved away from the input area, the function is called
        
In the function `saveCoffee(event)`, we see that:
- An element "spanEl" is defined as the next element of the result of a querySelector of an ID "realTimeStory". It ends up as the element of the span

- This span will change to green color "SAVED" as the spanEl's content and className get new values if "Enter" key is pressed

- Otherwise, this span will change to yellow color "EDITING"

- After that a function `printTagHTML()` is called

- Function `printTagHTML()` call for three more functions and give return values of three functions to three variables. These three values are the value of selection, value of checkbox, and value of radio button

- Then an empty string is initiated, template literals were used to concatenate the value of three variables to the empty string

-  Finally, the element with the class of "tags" was selected and the content was set to the string created in the previous step

In the function characterTyped(event), we see that:

-  The content of the result is set to event's value

- "pEl.nextElementSibling.classList.remove('hidden');" does not seem to be necessary

In the function `editingOff()`, we see that:

-  The yellow "EDITING" icon disappears from the result once mouse click on area other than the input area

The two buttons at the end can either save the content to have it reflected on the right, or reset everything to the defaulted states

- onclick event of the first button calls the function `saveCoffee(event)`, which is the same function as pressing "enter" in the text area

- onclick event of the second button calls the function `resetCoffee(event)`

- The `resetCoffee(event)` function set the values of all sections to their original defaulted values
:::

  - Explain the differences between `select`, `checkbox`, `radio`, `textarea` with regard to how we get the input `values`.
:::success
**RESPONSE:** 
`select`, `checkbox`, `radio`, `textarea` are HTML input types. `select` enables the user to choose one of the options while leaving them unselected if no shoice is made. `checkbox` allows for multiple choices, while `radio` forces the choice between one or another. Last, `textarea` leaves a space for the user to input their words, and is left in a default state or wording before the user writes in information.   
:::

  - What is the importance of the `name` attribute, especially for radio buttons?
:::success
**RESPONSE:** 
      The `name` attribute is important because it ensures that only one of the drinks can be selected. 
:::
  - Explain the significance of `e`, `banana`, `bananaEvent`, and `event`.
    - How are they the same and how are they different?
:::success
**RESPONSE:** 
`e`, `banana`, `bananaEvent` are variables of the functions that function as placeholders. `event` is different; it is a reserved word in JavaScript. `event` can have methods, such as .type, .key.  
:::

- Try tinkering with some of these functions to produce some diffent looking, behaving results in the results pane.
  - Explain what you tinkered with and what the results were.
:::success
**RESPONSE:**
We tinkered with some of the JS event functions, e.g. `resetCoffee`, but deleting those functions did not change the functionality of the inputs. In other words, coffee still showed up as selected. Perhaps that is because <i>coffee</i> is tagged as "checked" within the HTML. 
:::
---