---
tags: mstu5003, tinker, js
name: Eric Dios, Mingxin Qi, Yuxi Huang
---
# TINKER - Javascript Part II
<!--
- See repository: https://github.com/jmk2142/TodoMSTU5003
-->
- See demonstration: https://codepen.io/jmk2142/pen/oGxwPQ
- Tinker Markdown: https://hackmd.io/zJmA8GKJR5-Oe2Zy4r1wqw?both
<!--
For this week, the actual Markdown file is not available via Github Gists. I have included it within this week's Tinker repository along with the rest of the code. It is called `README.md`. You might want to `IMPORT` the markdown into hackmd.io to use that tool (recommended.)
To get access to this code, and the actual Markdown to play with, you can use Github to CLONE the repository using the Github GUI Client. You can get the idea of what repositories are in my Youtube Video:
## Github: How to clone my repository
You'll want to start with the video overview:
https://youtu.be/QOXhN90d9Mk?list=PLn93-yl6k7zUkSFNI8MQqmIVn017z8vKO
Since you want to copy MY repository, once you have the Github GUI Client installed - you can do so with one click of a button. Just click on the Clone or download option, then **Open in Desktop** and that will automatically open it up in the Git GUI. (See Below)

Keep in mind that since you are cloning my repository, you will only be able to commit changes to your local computer. You will not be able to _sync_ or _push_ changes to my Github repository - for obvious security reasons. (You wouldn't want just anyone to change YOUR code.)
If you would like to use Github for your work in progress, what you can do is **_FORK_** my repository first. (See _FORK_ button under account picture.) This will create a copy of this repository under your account name in Github. You can clone YOUR version of this to your local computer, then commit and push to your account to your heart's content. :smiley_cat:
---
-->
## Devtools
You will also want to watch this video on the `console` as we will be using it extensively to Tinker this week.
General Video on Console: https://youtu.be/GAqOggzH_GE?list=PLn93-yl6k7zUkSFNI8MQqmIVn017z8vKO
One of the most important tools we'll use is the `DEBUGGER`.
:::success
**Debugger Demonstration and Youtube Video**
<!--
REPO: https://github.com/jmk2142/Debugger
DEMO: https://jmk2142.github.io/Debugger
-->
CODE: https://codepen.io/jmk2142/pen/RwZErre
DEMO: https://cdpn.io/jmk2142/debug/RwZErre
YOUTUBE: https://youtu.be/RdF7j4no0Ts
:::
I recommend that at some point, you watch these demonstrations and use these tools to explore the Tinker.
:::info
In order to use `console.dir(object)` and see the object property/values, make sure your console setting is set to DEFAULT.

:::
## Tinker GIST: TODOS
> Good bye, "Hello World!"
`Hello World` is probably the most common introductory program around as it's so simple.
```javascript=
alert("Hello World!");
// Or alternatively...
console.log("Hello World!");
```
Unfortunately, it's not very useful. It doesn't really show the range of different programming concepts and to be quite frank, it's boring. Many beginners like us are interested in creating interactive applications and this requires a range of programming concepts.
1. HTML Elements
2. CSS
3. Variables
4. Operators
5. Functions
6. Control Statements
7. Events
8. Data Structures + Data (e.g. Arrays, Objects, Booleans, Numbers, Strings)
And you really cant get a sense of how these things work together with a 1 line program like `Hello World!`.
### Enter TODOS
Some clever programmer realized this and probably thought:
> What's the simplest, _real_ program I can build that will incorporate all the important aspects of a basic interactive program?
And the **TODOS** or **TODO LIST** program was born.
The beauty of TODOS is that it has everything in a pretty simple package. It can be solved using a variety of different strategies and can be created to be _simpler_ or _more sophsiticated_ depending on ones needs. It tends to now be the defacto standard for demonstrating a full interactive application.
Beginners AND advanced students alike build TODO apps as they learn new things. For example, our TODOS Tinker is designed to demonstrate the base JS concepts with a few _stretch_ challenges embedded in it. In my regular practice, when I have to learn a new library or framework, I will probably start by viewing an existing TODO app built with that specific library to see how that library works. Sort of like how you might compare a basic HTML page with a Bootstrap page (of the same content) to be able to compare and contrast the two. If you're interested, you can briefly look at [this page](http://todomvc.com/) which is an archive of the TODO application built in various different frameworks.
And this is where I am hoping to take this class, the culmination of all the things we've been working towards - to understanding this first, real, interactive program and hopefully - you can apply some of these concepts in your own works.
## Tinker Tasks
In this tinker, were going to:
1. Review prior concepts in this new context:
- Variables, functions, events, and arrays
2. Observe, analyze, and study new concepts:
- Control statements (E.g. `if`, `for`)
- Logical operators (E.g. `===`,`&&`, `||`,`<`,`<=`,`>`,`>=`, etc.)
- Objects (and `array` of `objects`)
3. Learn how to use more developer tools to study JS code
- Source (i.e. debugger)
- Console (i.e. `console.log`, `console.dir`)
We will continue to observe, analyze and think about this program in terms of:
> What is the STATE?
> What is the SEQUENCE?
> What is the CAUSALITY?
### Part 0: Conceptual Program Overview
Play with the program and observe how it reacts to user interactions.
- _Without_ talking about it in _programming terms_ explain the user observable steps/process of the following three interactions and how the program responds.
- Adding a todo
- Completing a todo
- Removing a todo(s)
>> This application works similar to any other To-Do list. You can add, remove and check off items that the user inputs.
Be specific but imagine you are talking to a _non-programmer_. Think about this in terms of observable actions and reactions.
> User puts toast in the toaster. Sets the length of the timer. Pushes the lever to start the toaster. The toast pops out the toaster after the time is completed and goes "DING".
- For each of the interactions above write in _pseudocode_ the steps of how the program for that interaction unfold and results. Pseudocode is semi-formal structure to write out the gist of how your program would work. It uses some keywords but is largely language agnostic. There isn't a single correct way to do it but the following are some rules that can help.
- RULES:
- One statement per line
- CAPITALIZE initial _keywords_
- READ, WRITE, IF, ELSE, REPEAT, UNTIL, AND, OR
- Indent to show hierarchy and groups of operation
- Keep statements language independent
```markdown=
# Making toast for a big family
READ loaf of bread
READ slice of loaf
Put slice in toaster
WRITE time to toast
Start the toaster
Cook the toast
READ time
WRITE time by one second less
REPEAT UNTIL time is zero
Remove toast
REPEAT for all slices in loaf
# Serving toast
WRITE number of slices total
READ number of family members
READ toastiness
IF toast is burnt AND (total slices >= number of family members)
throw away toast
decrement slices total
ELSE
serve toast to family member
```
- Using your pseudocode, identify the function(s) in the actual JS code that relate to your pseudocode.
- Compare and contrast your pseudocode with the actual code.
- Explain what similarities and differences you noticed about the instructions / steps / processes in the code vs. your psuedocode.
```javascript=
# adding a todo
PUT information in textbox
CLICK "Add" button or ENTER
READ information in textbox
ADD information on the list
# completing a todo
READ a todo item
CLICK the radio
READ the crossed-down todo item
# removing a todo(s)
SEE the red button
CLICK the red button
READ the chosen item disappears AND the button CHANGES to grey color
```
>> Comparison to JS:
>> -User interactions (at the basic level) are the same; add & remove.
>> -The visual representation is similiar via the use of a add & remove button.
>> -Our pseduocode did not neccesarily involve the creation of the template (the format, the CSS etc.) which actually makes the list (ours kind of just existed)
>> -Our pseudocode does not represent the (if,else) functions of actually enabling the code to create/modify the TO-DO list
>> -Our pseudocode does not have the process of grabing the data after the user input.
>> -Our pseduocode does not represent what "nothing to do" looks like.
- Manipulate different parts of the code as you see fit. Why did you decide to manipulate that part? What happened? (More structured tinkering to follow.)
>> While using debugger we decided to manipulate the functions associated with the add button. We thought this would be a good part to manipulate as there were so many functions assoicated with adding a task.
>> We removed JS lines 96-99 to begin which removed the ability for the user to toggle complete/incomplete tasks.
>> Knowing that the timestamp was critical to the operation of the JS we removed lines 84-86 (the timestamp) and as we thought the code failed to function.
>> We removed the parameter from line 103 `Function removeTodoItem (event)`. After removing `(event)` it seemed that nothing changed in terms of the the Todo list functionality.
### Part 1: Variables, Functions, Arrays, and Events
- Explain the `data` variable.
- What does this data (and the data inside) represent conceptually?
>> Conceptually the data is the default example. It provides the characteristics which make up each "TODO Task." IE. the ID (timestamp it was entered onto the list, Task to be completed and its completion status.)
- If I wanted to access the second object, how would I do that in code?
>> `Function getTodoData (1497141913701)`
- If I wanted to access the `done` property of the first object, how would I do that?
>>Function `getTodoData (1497141891479)['done']`
- Look through the rest of the code where this `data` array is used. When the user does things, am I manipulating the visual display and updating the data to reflect those changes? Or am I manipulating the data and updating the visual display to reflect those changes?
>> The user updates the visual display and those changes manipulate the data.
- Is this what you would have thought of?
>> It seems intuitive that the user would be making changes to the list from which the JS reacts yet in class we have also seen the computer taking data from user inputs ie. fillable forms which create printlogs of user information.
- What might be the significance of this program design decision?
>> A ToDo list is based on the user's requirements. In other cases the JS would be utilized to take and compile information on behalf of the website owner.
- What do these lines in my code do?
```javascript=
var todosEl = document.querySelector('#todos');
var inputEl = document.querySelector('input');
var completedEl = document.querySelector('#counter');
```
>> These elements make it clear what is being referenced. By having "plainspeak" language the programmer can quickly associate information/data to an element like `#todos` or `input`.
- Why declare these (see above) variables at the Global scope instead of in the functions?
- Or not at all... (E.g. `document.querySelector('#todos');`)
>> These general variables will be utilized in multiple and various functions. By making their initial declaration it is clear to programmers what variables are being called upon.
- The `toggleComplete` function has an event parameter. Inside the function I access `event.currentTarget`. What is the difference between `event.currentTarget` and `event.target` which we used previously?
>> See line 244.
- Hint 1: You can add a `console.log(event)` etc. inside that function to test the value of `event.target` and `event.currentTarget`.
- Hint 2: When testing, click on a todo to "complete" it. Click on two areas: the `li` as well as the `i` (font icon) element to see the differences.
- Hint 3: You can pass multiple arguments to `console.log()`. I often pass two: first a string label, second the thing I want to log. This will basically make the logs easier to identify if you use `console.log()` a lot.
```javascript=
console.log("SOME LABEL: ", dataToLog);
```
>> Both of them are the response of crossing down the items on the list, while `event.currentTarget` refers to the new variable the user adds, and `event.target` refers to the default varibale the code already has.
- In the `toggleComplete` function, there is a `event.currentTarget.id`. Is that `id` the same thing as the id property in my todo objects in the `data` array?
- Explain.
>> Yes, they are randomly date numbers generated by `getTimeStamp`, both of them symbolize the unique tag helpful in other commands grab the data.
- What does `!something` mean? (The exclamation mark) and how is it used in this code when we `toggleComplete`?
>> The Logical Not Operator `!` takes true to false and false to true (Toggling). The `onlclick` of the radio button/task will designate the task as complete or incomplete.
- Try calling some of the functions directly from the console. Some will work. Some won't.
- Explain what you find.
>> `Function markAllComplete` was the only function that worked for us and it returned the timestamp. It was a little strange we couldn't get any other functions to work.
- Look at the function declarations in the JS panel.
- _Where_ is each function being called?
>> Functions are both called from other functions and from the global scope.
>> Example: Creating a new task -> `function addToDoItem`, `FunctionValidateTask` (when true)--> `functiongetTimeStamp`--> `newTodo.task=inputEl.value`; etc.
- _When_ is each function, actually called?
>> When the user has interaction with the page through either `onEnterKey` or `onclick`
>> When the new variable is added to the ToDo List (`function addToDoItem`) and the user clicks add.
- What parameter(s) does that function have?
>> event;
>> task;
>> id.
- What is the argument that is passed into the function when it is called?
>>Some functions are called by value, and some are called by address and name. When the function is called, it will run again and output a result.
- Use the console (in Chrome devtools) to `console.log()` and `console.dir()` the following. What is the difference between `console.log` and `console.dir` and why is `console.dir` kind of more useful for looking at some kinds of data?
```javascript=
console.log(data);
console.log(todosEl);
console.dir(data);
console.dir(todosEl);
```
>>console.log provides code/html. console.dir calls back the element/object. Depenedent on what you are trying to accomplish each console action can provide you more appropriate information.
### Part 2: Objects and Arrays of Objects
- Manipulate the different _properties_ of the _objects_ inside the `data` array.
- Change all todo objects' `done` property to `true`.
- Change some of the task values.
- Run your code and explain how this changes what you see and why.
>> We did not notice any change in doing so. We both changed the task values and added new tasks but there was not a noticeable difference between the function modification.
- `console.dir()` the `data` array. Goto the console and _OPEN_ the `> Array(3)` text by clicking on it. Go deeper by opening up the nested objects. Analyze what you see. Then add a new todo through the user interface. `console.dir()` the `data` array again and investigate the insides.
- What is the difference between `data` before and after adding a new todo?
>> ----Revisit---, as once again no noticeable changed was observed.
- Run the following code:
```javascript=
data.push({
done: true,
task: "Goto Aikido Lessons",
id: getTimeStamp()
});
console.dir(data);
```
- What did the code above do?
>>Within the code the task of Goto Aikido Lessons was inserted an maked complete. It was fairly easy to recognize that would have happened.
- Does our page reflect the changes made? Why or why not? Prove it.
>>Yes, the page now shows the completion of the Aikido lessons after the insertion of the designated code.
- Does order matter in `Objects`?
>> Not always, in this case the timestamp will designate where in the task list the task will be placed. In lieu of a timestamp the order may become critical to the order of the tasks.
- What is the difference between `Object` keys (E.g. `done`, `task`, `id`) and `Array` indices (E.g. `0`, `1`, `2`)?
- How are they similar?
```javascript=
var myAry = [123, "Code", true];
var myObj = {
id: 123,
task: "Code",
done: true
}
console.log(myAry[1]);
console.log(myObj["task"]);
console.log(myObj.task);
```
>>
- Compare the following in the console:
```javascript=
var element = document.querySelector('ul');
var author = { first: "Mark", last: "Twain" }
var example = {
theAnswer: 42,
student: true,
hobby: "Fishing",
sayHello: function(){
alert("Hello");
},
favNums: [1,2,3],
favAuthor: author
};
console.dir(example);
console.dir(el);
```
- What is an `element` really?
>> We would like to provide our version but we stumbled upon its articluation. However, the following definition concisely describes an element. They are the objects, the things, the variables...
>> The Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. Reference (https://developer.mozilla.org/en-US/docs/Web/API/Element)
- How does our `element` relate in terms of similarities and differences to `example`?
>> They are both a list of data, the format is the same in this way. They are different as example is what is coded by us the element uses the documentquery selector to pull information from the HTML.
- If I wanted to call the function in the `example` object, how would I do that? Prove it.
>>function example
console.dir (example);
```
- Try the following code in the console. How does dot notation and bracket notation differ and why would you want to use one or the other?
```javascript=
var x = "username";
var user = {
username: "happyCat"
}
console.log(user.username);
console.log(user["username"]);
console.log(user[x]);
console.log(user.x);
```
- Identify various areas where the `.` object notation is used and explain the thing on the left side of the `.` and the thing on the right side of the `.`
- E.g. `document.querySelector()` `document` is... `querySelector` is...
- HINT: There are MANY choices here.
>>>
>>>`User` is an array. `Username` is an object in this array. Therefore, when we use user.username, it returns happyCat, the value of `username`.
>>>The `["username"]` also works because this is another way to get the value. It is the same as user.username.
>>>`user[x]` means get the object in this array.
>>>But `user.x` doesn't work because there is not a property named "x". So we cannot get the value of it.
- In two areas of my code, I use what is called a `filter` function. It's a function that arrays can use like `list.pop()`, `list.push()`.
- How does a filter function work?
>> It calls upon what is being filtered for. This is by creating a new array with the elements that have been filtered for without changing the original arrary.
- What is the significance of the function argument that is passed INTO the filter parameters?
>>It is the orginal array however, it will not be changed but rather filtered through the new function.
- With regard to the function that is passed into the filter as an argument, that function must `return` a boolean or evaluate to a boolean. What is the purpose of this?
>> Because that is the purpose of the filter. To pass an array through the filter and keeping only what is being filtered out without compromising the orginal array.
- What does the _filter function_ return?
E.g. `var x = list.filter(...); // What was returned to x?`
- CAUTION: NOT the function argument that goes into the filter.
- HINT: If you don't know, can you use console to "test" an idea out?
- Does filtering an array _change_ the original array?
>>No, it does not as referenced prior
### Part 3 Control Structures
- I use the `if` statement in several places in this code. Explain why a conditional is necessary in:
- `updateTodoItems`
- `updateRemoveButton`
- `onEnterKey`
- `validateTask`
- `addTodoItem`
- `getTodoData`
- HINT: You might want to `console.log` the boolean condition where you see the `if` statements to understand what condition we are evaluating.
```javascript=
if (booleanCondition) {
...
}
console.log(booleanCondition);
```
- Comment on how the boolean condition works as there are many different examples.
>> `updateTodoItems` has two `if` statement, the first works as crossing down the new item or not (true for crossing down, false for not crossing down); the second work as displaying the text hint "Nothing todo ..." or not (the text will show up once the user corsses down all the items).
>> `updateRemoveButton` works as adding values on the number of the Remove button or not (true for changing the text content, false for not).
>> `onEnterKey` works as cilcking enter key will add a new item to the list or not, ture for having bee clicked the key and adding a new item while false for not having been clicked.
>> `validateTask` works as testing if the new-added item works successfully or not, true for the item has been updated on the list while false for not.
>> `addTodoItem` works as displaying the new-added item or not (true for displaying it, false for not), after running the `validateTask` command.
>> `getTodoData` also has two `if` statement, the first works as searching and defining the new item in the data set or not, true for searching and defining it while false for not; the second works as caching the new item to the data set or not, true for caching it while false for not.
- In this code, there are two kinds of `for` loops. The more traditional that looks like:
```javascript=
for (var i=0; i < list.length; i++) {
// CODE
}
```
and a `for of` loop that looks like:
```javascript=
for (item of list) {
// CODE
}
```
- How does a `for of` loop work?
- What does the `item` represent? (It can be named anything: `x`, `item`, `thing` etc.)
>> The `for of` loop iterates over iterable objects including string, array: "it invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.(quoted from MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)". In our example, `for of` loop in `updateTodoItems` function stands for each set of objects in data variable named "todo", grab todo data for following execution.
- Why are `for of` loops convenient compared to the traditional `for`?
>>`for of` loops use more concise code to run iterable objects and to get their values.
- For what purpose(s) do I employ a `for` or `for of` loop in this program?
>> `for` loop in `getTodoData(id)` function uses as explicitly displaying the iterated process of searching and defining a new item's values.
>> `for of` loop in `updateTodoItems` function uses as iterating new items into the data variable, which is just an array).
- On Facebook or Pinterest, or Twitter, how does a loop through data relate to the display of content?
>> Take Twitter as our example: adding a new tweet will change the original state of length and returns to the display of new-added one with the previous content.
### Part 3 Specific Routines
- Take a look at the `updateTodoItems`. Comment it out and replace it with this alternate, but functionally identical version. How does this function work and how do they relate / differ?
```javscript=
function updateTodoItems() {
todosEl.innerHTML = "";
if (!data.length) {
var liElement = document.createElement('li');
liElement.innerText = "Nothing todo...";
todosEl.appendChild(liElement);
} else {
for (todo of data) {
var liElement = document.createElement('li');
var iElement = document.createElement('i');
liElement.id = todo.id;
liElement.onclick = toggleComplete;
if (todo.done) {
liElement.className = "complete";
iElement.className = "fa fa-check-circle-o";
} else {
iElement.className = "fa fa-circle-o";
}
liElement.appendChild(iElement);
liElement.innerText = todo.task;
todosEl.appendChild(liElement);
}
}
updateRemoveBtn();
}
```
>> Both of them are functioning as adding a new item into the todo list, the difference is that when running `updateTodoItems` function, the original one is to first cach the input value in the variable data, and then create a new line with the text in the todo list on the screen; the example above is to first create a new, blank line in the list on the sreen, and then fill the entered value in the variable data and the new line.
- Take a look at the helper function `getTimeStamp`. This function will return a number, in milliseconds, the current time stamp since January 1, 1970.
- I call this when I create new todo items, what are some ideas as to why I might be using a timestamp for todo `ids`?
>> We think that the timestamp (a series of random numbers) works as an unique ID card for each items in the todo list, preventing items with the same data.task.textContent from being confused in the following commands.
- Take a look at the incomplete functions `markAllComplete` and `updateItemsLeft`.
- Can you complete these and add the functionality to this app?
>> function `markAllComplete` :
```
<html>
<div class="controls">
<button onclick="markAllComplete()">All Completed</button>
</div>
<script>
function markAllComplete() {
var incompleteTodos = data.filter(function(todo){
return todo.done = true;
});
data = incompleteTodos;
updateTodoItems();
var completedTodos = data.filter (function(todo){
return todo.done = true;
});
completedEl.textContent = completedTodos.length;
if (completedTodos.length) {
completedEl.parentElement.disabled = false;
} else {
completedEl.parentElement.disabled = true;
}
}
</script>
</html>
```
>> function `updateItemsLeft` :
```
<html>
<div class="controls">
<button onclick="updateItemsLeft()" id="check">Checked</button>
</div>
<script>
var leftEl = document.querySelector('#check');
function updateItemsLeft() {
var incompletedTodos = data.filter(function(todo){
return todo.done === false;
});
leftEl.textContent = "You have " + incompletedTodos.length + " tasks left ";
if (incompletedTodos.length) {
leftEl.parentElement.disabled = false;
} else {
leftEl.parentElement.disabled = true;
}
}
</script>
</html>
```
### Part 4 Debugging, Tools
Using the Chrome debugger (source) tool create breakpoints and watch the program execute line by line, part by part. Experience how this tool can give you insight into your program's _STATE_, _SEQUENCE_, _CAUSALITY_.
#### Chrome Debugger
- Set breakpoints at the following locations of your program
- `function initializeTodos`
- `function onEnterKey`
- `function addTodoItem`
- `function toggleComplete`
- Use the `Step over the next function call` feature to watch how the program pauses during the _SEQUENCE_ of its routines.
>> In this process, when a function contains sub-functions, the computer treats the sub-function as a complete step rather than locating the sub-function and process in detail. The process of calling the sub-function is not showed to us but the instruction is executed.
- Use the `Step into the next function call` feature to watch how the program pauses during the _SEQUENCE_ of its routines.
>> When we clicked `Step into the next function call`, the program pauses step by step in detail. The sub-functions are also presented and processed.
- What is the difference between `Step over` and `Step into` and how does this help you understand programs?
>> The difference is whether the execution process of the sub-function is presented in detail. If we want to understand the details, we can use `step into`, but when the function is more complex, `step over` can help us analyze the function and steps more quickly and clearly.
- Use `Step into` until you've reached the line `var inputEl = document.querySelector('input');`. Should be highlighted in blue.
- Highlight the variable `todosEl` on the line before it and `right click` on it. Select _Evaluate in console_.
- What does the console print?
- Highlight the variable `inputEl` on this highlighted blue line.
- Why does the console say `inputEl` is undefined?
>>It means the console does not explicitly return something.
- When you step through your code, does the blue line represent code that is about to be executed or code that has already executed? How do you know?
>>The blue line represent code that has already executed. Becuase when we put the cursor there, we will see the updated data in the list.
- What do you predict would be the console value of the variable `completedEl` on the next line if you _Evaluate to console_ at this point?
>>Undefined(not sure).
- Watch how debugger annotates your source code with the updated _state_ of different variables as your program progresses.
- How does the debugger behave when you enter a loop in your program?
>> It will follow the code and finish the loop step by step until all operations are completed.
- How does the debugger behave when you reach the a `filter` function call?
>>`filter()` is used at the function related to remove ToDos. For example, the debugger process step by step in the function `removeTodoItem()`. At the last step of this function, `updateTodoItems()` is called. And the items on the page are changed as a result.
- What does filter do and how does it work?
>>`Filter()` applies the function to each element, and then decides whether to keep or discard the element based on whether the return value is true or false. It iterates over the existing values and process by returning `todo.done === true/false`.
### Part X: Putting all together
**Explain the program line by line with sufficient details, part by part.**
:::success
- Line by line
- Part by part
- Be sure to copy blocks of code into this markdown using code formatting/fences as references to your explanations.
- For repetitive code, you can explain how a line works then summarize how it would work for the rest.
:::
> HTML
>> `<head>` sets the title of the webpage and imports the css style from an outside link.
```
<head>
<title>Todo List</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
</head>
```
>>Body
>><body>
>><h1>TODO List X</h1>
<ul id="todos">
<!-- ITEMS HERE -->
</ul>
>>This section includes the header title of the list (TODO List) and the unordered listing of tasks structure `"todos"`
>> div
```
<div class="controls">
<input type="text" onkeypress="onEnterKey(event)">
<button onclick="addTodoItem()">Add</button>
<button onclick="removeTodoItem()"><span id="counter"></span> Remove</button>
</div>
<a href="https://codepen.io/jmk2142/pen/LzNLqM" target="_blank">Simple Version</a>
</body>
```
>> This section of the HTML provides the most critical elements which include the variables of `'#todos', 'input' and ''#counter'`
>> Via clickable buttons the user can write tasks, add tasks and remove tasks from either a click of the button or by pressing enter (in the case of add).
>> the <a href section provides a simple version of the task list which does not include the bootstrap stylization which for us as programmers can "blur" some of the code. The link is also within the codepen domain.
> Javascript
```
var data = [
{
id: 1497141891479,
task: "Wake up",
done: false
},
{
id: 1497141913701,
task: "Eat breakfast",
done: false
},
{
id: 1497141937545,
task: "Learn code",
done: true
}
];
```
>> This block defines the default information named `data` with `id`, `task`, `done` properties.
```
var todosEl = document.querySelector('#todos');
var inputEl = document.querySelector('input');
var completedEl = document.querySelector('#counter');
```
>> It defines three new variables to make the `document.querySelector` part more clear and easy to refer. These variables are used in the following functions, reflecting the basic interactions on the webpage: displaying items (`todosEl`), adding new items (`inputEl`) and crossing down items (`completedEl`).
```
function initializeTodos() {
updateTodoItems();
}
function updateTodoItems() {
var todosHTML = "";
for (todo of data) {
if (todo.done) {
todosHTML += `<li id="task-${ todo.id }" class="complete" onclick="toggleComplete(event)">`; // Display the completed items
todosHTML += `<i class="fa fa-check-circle-o"></i>`; // Font-awesome
} else {
todosHTML += `<li id="task-${ todo.id }" onclick="toggleComplete(event)">`; // Display the uncompleted items
todosHTML += `<i class="fa fa-circle-o"></i>`; // Font-awesome
}
todosHTML += `${ todo.task }`;
todosHTML += `</li>`;
}
if (todosHTML === "") {
todosHTML = "<li>Nothing todo...</li>";
}
todosEl.innerHTML = todosHTML;
updateRemoveBtn();
}
```
>> We explained what each part does in the code part above by "// + content". In short, the `updateTodoItems()` function is to provide a template and then add the information which users input to the webpage. Everytime the items are changed, this function will be called.
```
function updateRemoveBtn() {
var completedTodos = data.filter(function(todo){
return todo.done === true;
});
completedEl.textContent = completedTodos.length;`
if (completedTodos.length) {
completedEl.parentElement.disabled = false;
. } else {
completedEl.parentElement.disabled = true;
}
}
```
>> This function removes completedTodos and knows they are completed because the todo.done state is true. Meanwhile, it updates the number showing on the Remove button.
>>**
```
function onEnterKey(event) {
if (event.code === "Enter") {
addTodoItem();
}
}
```
>> When the enter key is clicked the item wil be added to the ToDo list. (The user may also click the button however, this function strictly enables the press of the enter button.)
```
function validateTask(task) {
if (task !== "") {
return true;
} else {
return false;
}
}
```
>>It means if the task is existing (the user has typed something here), it will be a validated task and it will process further to `addTodoItem()`.
```
function addTodoItem() {
if (!validateTask(inputEl.value)) {
return;
}
var newTodo = {
id: getTimeStamp()
}; // It gives the new item a template id generated by `getTimeStamp (return a series of number)`
newTodo.task = inputEl.value;
newTodo.done = false;
data.push(newTodo);
updateTodoItems();
resetInput();
}
```
>> It means that if the task is validated, the newTodo's value will be read and add to the list. The `newTodo =` part is to give the new item an template id. Then the `updateTodoItems()` function will be called and the list will be updated.
```
function toggleComplete(event) {
var todoID = parseInt(event.currentTarget.id.replace('task-',''));
var todoData = getTodoData(todoID);
todoData.done = !todoData.done;
updateTodoItems();
}
```
>> Enables the toggling (clicking) of items as completed. It uses the todoID to locate the data related to this id and then mark it as completed.
```
function removeTodoItem(event) {
var incompleteTodos = data.filter(function(todo){
return todo.done === false;
});
data = incompleteTodos;
updateTodoItems();
}
```
>> Deleting all items shown on the todo lists by clicking the Remove button.
```
function resetInput() {
inputEl.value = "";
}
```
>> Clearing the cached values from state so that the input placeholder can be filled new texts in it.
```
function getTodoData(id) {
var todoFound;
for (var i=0; i < data.length; i++) {
if (data[i].id === id) {
todoFound = data[i];
// var indexAt = i;
break;
}
console.log(data[i].id === id);
}
if (todoFound) {
return todoFound;
} else {
return null;
}
console.log(tofoFound);
}
```
>> Running a loop for keeping locating the set of objects in data variable, defining it as a new object named "tofoFound". If no value is adding in the list, the function will return null, otherwise it will create a new tofoFound object.
```
function getTimeStamp() {
return Date.now(); // this returns a timestamp in milliseconds since 1970.
}
```
>> Generating an unique id for each set of objects in the data variable.
**Make it yours (group's)**
:::success
- Try to extend this program to do something cool, as a group, your own original idea(s).
- What is something that a Todo list or todo list user might benefit from?
:::
>> We can add a date after each item so that the user can know when he/she created the list and when the list was completed.