sl5137
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: mstu5003, tinker, js --- # TINKER - Javascript Part II :::success Group Members: Justin Arenas (ja3688) Sihan Lu (sl5137) Date: December 11, 2022 <span style="color:blue"><i>Note: All of our answers are noted in green.</i></span> ::: ## 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) 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. :::success The actual code starts with the `initializeToDo` function and is more sophisticated than our psuedocode due to having more code lines and machinations. ::: - Explain what similarities and differences you noticed about the instructions / steps / processes in the code vs. your psuedocode. :::success We created a simple psuedocode for the purposes of the exercise; however, we did that based on recognizing the complexity of the actual code and wanted to make an obvious comparison built of simplicity. ::: - 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.) :::success We manipulated various parts of the code to see how changing the code would change the user interface, display, and functionality and synergy of the different elements. We also reviewed the JavaScript for comparison purposes. ::: ### Part 1: Variables, Functions, Arrays, and Events - Explain the `data` variable. - What does this data (and the data inside) represent conceptually? :::success It is a collection of array objects, which enable to add afterwards functions to the list. ::: - If I wanted to access the second object, how would I do that in code? :::success `console.log(data['1'])` ::: - If I wanted to access the `done` property of the first object, how would I do that? :::success `let allDone = data.find(todo => todo.done === false); console.log(allDone);` ::: - 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? - Is this what you would have thought of? - What might be the significance of this program design decision? :::success Manipulating the data and update the visual display. It is easier for us to decide the sequence and layer to test any mistakes in logics of the code if we manipulate it to generate the display. So the situation like: where is the function of this button? why is it not working? can be less frequent to distract us. ::: - What do these lines in my code do? ```javascript= var todosEl = document.querySelector('#todos'); var inputEl = document.querySelector('input'); var completedEl = document.querySelector('#counter'); ``` :::success - Line 1 signals to the program to find all of the to-do list elements labeled with the id #todos within the HTML and associate them with the variable `todosEl` accordingly - Line 2 signals to the program to find all the 'input' value programmed into the HTML and associates them with the set variable `inputEl` - Line 3 signals to the program to find the `id=counter` within HTML and defines it with the variable `completedEl` ::: - Why declare these (see above) variables at the Global scope instead of in the functions? - Or not at all... (E.g. `document.querySelector('#todos');`) :::success Because these are important elements that we might use in different function to achieve multiple interactions with the same id. We want to avoid duplication and the risk of forgetting to define those variables. ::: - 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? - 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); ``` - 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. :::success ![](https://i.imgur.com/k4Ig6ox.jpg) For the `currentTarget.id`, when we click on the blank line area, it will find the id of the element that attached, whereas `target.id` will only refering to the id of the element trigger that event, so when we console.log it, the console will show "" instead of the target id of that element. ::: - What does `!something` mean? (The exclamation mark) and how is it used in this code when we `toggleComplete`? :::success "!" set all boolean to a reverse value (true to false, false to true) ::: - Try calling some of the functions directly from the console. Some will work. Some won't. - Explain what you find. :::success ![](https://i.imgur.com/vibVrH4.png) When adding a new task to the list, it will show undefined in console. ::: - Look at the function declarations in the JS panel. - _Where_ is each function being called? :::success Typically they are called at the end of the function. ::: - _When_ is each function, actually called? :::success The functions relates to the todo list was called under `function updateTodoItems()`, including `updateRemoveBtn();` `updateItemsLeft();` `updateMarkAllCompleteBtn()`. Other functions relate to the `updateTodoItems`, such as `function sortData(s)` called update function inside its own function. ::: - What parameter(s) does that function have? :::success In terms of the addToDoItem function, the parameters include event, task, and item. ::: - What is the argument that is passed into the function when it is called? :::success `todoData.done = !todoData.done` ::: - 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); ``` :::success `console.log()`will ouput the final value of this function whereas `console.dir` will log an interactive list of the object with all its properties. ::: ### 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. - `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? :::success After adding a new todo, the original array would contain a new object that contains its respesctive properties, including `task`, `id`, etc. to the data array. ::: - Run the following code: ```javascript= data.push({ done: true, task: "Goto Aikido Lessons", id: getTimeStamp() }); console.dir(data); ``` - What did the code above do? :::success The given code adds a new task, "Goto Aikido Lessons," to the todo list given that it is a new entry to the data array. ::: - Does our page reflect the changes made? Why or why not? Prove it. :::success The page does not reflect the changes, they are only reflected in the code, until we interact with the todo list, which forces the data array to "refresh" and shows the change we made to the code. ::: - Does order matter in `Objects`? :::success Yes, the order matters because the visual display depends on `Objects` establishes the orders of things. ::: - What is the difference between `Object` keys (E.g. `done`, `task`, `id`) and `Array` indices (E.g. `0`, `1`, `2`)? :::success The difference between `Object` keys and `Array` indices lies in the fact that the former serve as identifiers that can be used to lookup data to identify given values, whereas the latter indicates the position values are stored within an array. ::: - 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); ``` :::success Both are similar because they can be used for data extraction purposes. ::: - 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(element); ``` - What is an `element` really? :::success An `element` is a component within HTML, and within the given code, it is a variable associated with `ul`, which produces the unordered list. ::: - How does our `element` relate in terms of similarities and differences to `example`? :::success Both possess various properties, but example produces an object, whereas an element produces an array. However, both produce undefined outputs when we input them into the console. ::: - If I wanted to call the function in the `example` object, how would I do that? Prove it. :::success To call the function in the `example` object, you would use `console.dir(example.sayHello)`. ::: - 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); ``` :::success Bracket notation is different from dot notation because it is more difficult to read and slower to write. However, it is helpful for working with information assigned to variables. Dot notation cannot work in the same manner with variables, but it is faster and more accessible for reading purposes, which is why it would be more desired to use than bracket notation. ::: - 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. - .(string) not.(property) :::success Suppose we use the given code from Part 1, which uses the .object notation: ```javascript= var todosEl = document.querySelector('#todos'); var inputEl = document.querySelector('input'); var completedEl = document.querySelector('#counter'); ``` Here, the variable `inputEl` is assigned to `document.querySelector`. Thus, the webpage serves as the document through which we want the program to use `querySelector` as a means to find an element within the HTML specific to given argument `'input'`. ::: - 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? :::success The filter function applies a boolean (true/false) argument to an array and produces a new array with elements that satisfy the testing of the given argument. ::: - What is the significance of the function argument that is passed INTO the filter parameters? :::success The filter function helps to create the new array based on which elements adhere to the given test. Those array elemets are passed through the filter parameters, which produces a change via the new array, but not the given parameters. ::: - 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? :::success The purpose of returning or evaluating a boolean is to signal to the program which elements of the given array should pass to the new array based on the filter function. ::: - 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? :::success The filter function applies a boolean (true/false) argument to an array and produces a new array with elements that satisfy the given argument. ::: - Does filtering an array _change_ the original array? :::success No, filtering an array does not change the original array. Instead, it leaves the orignal array in place and creates a new array comprised of the elements that match the given boolean condition. ::: ### 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. :::success In the `function(updateTodoItems)`, when we adding new todo item to the list, the function will show the todo list. In the console, the new item shows in format of the array `data`. When we mark the item as complete, it shows undefined in console. ::: - 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.) :::success The `item` receives a value from the sequence on each iteration. ::: - Why are `for of` loops convenient compared to the traditional `for`? :::success Because it contains less codes than the traditional one, so the possibilities of write down wrong syntax is lower. Furthermore, the `for of` typically is more accurate when looping through arrays. Sometimes the traditional one may not print one item in that array. ::: - For what purpose(s) do I employ a `for` or `for of` loop in this program? :::success When we have multiple objects in the array, it is better to use `for` and `for of` to locate and find the exact thing we want to show on the page. By using loop, it is also easier to set a format for all items in the array, which is more efficient. ::: - On Facebook or Pinterest, or Twitter, how does a loop through data relate to the display of content? :::success When users browse the content, those platform definitely want contents to show in the same format to achive a better interaction experience. When contents being printed out in the same form, users can know where to click to find information they want, such as account, likes and follow. With millions of content generated each day, we also want the website respond more quickly, using loop is more efficient as well. ::: ### 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(); } ``` - 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`? :::success In order to print the time stamp of the completed todo item, we need to call another function to get the property "id" in a new object. ::: - Take a look at the incomplete functions `markAllComplete` and `updateItemsLeft`. - Can you complete these and add the functionality to this app? :::success ![](https://i.imgur.com/b2v1RbV.png) ![](https://i.imgur.com/GMB6lOS.png) ::: ### 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. - Use the `Step into the next function call` feature to watch how the program pauses during the _SEQUENCE_ of its routines. - What is the difference between `Step over` and `Step into` and how does this help you understand programs? :::success Step into will go through the test step line by line when debugging. When the function gets called, step into will enable us to test into each line of that function. Step over also can be used to test the procedure but it won't go into the called function line by line, the entire procedure call will be executed as a single step. ::: - 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? :::success ![](https://i.imgur.com/Iq191jV.png) ::: - Highlight the variable `inputEl` on this highlighted blue line. - Why does the console say `inputEl` is undefined? :::success Because there is nothing being typed into the form so there is no value being assigned to the varaiable. In the console, it shows `undefined` ::: - 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? :::success The blue line represent the code that is about to be executed. Becuase the step feature will go through the code in other function that has not yet being called, if you continue clicking on the `step into`. ::: - 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? :::success `updateItemsLeft();` ::: - 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? :::success It will go through the loop function procedure for several times until the loop ends. ::: - How does the debugger behave when you reach the a `filter` function call? :::success It went through the `return todo.done === true;` three times (since there are three items left in the list). ::: - What does filter do and how does it work? :::success Check the status of the items, update the status of the items in the array. The filter can filter down the to just the elements from the given array, then the update function is called to show the updated new list. After it done with the filter process and select new arrays from`return todo.done === true;` the code will go to next line of `completedEl.textContent = completedTodos.length;` ::: ### Part X: Putting all together **Explain the program line by line with sufficient details, part by part.** - 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. <b>HTML:</b> :::success ```javascript= <ul id="todos"> <!-- ITEMS HERE --> </ul> <div class="controls"> <input type="text" onkeypress="onEnterKey(event)"> <button onclick="addTodoItem()">Add</button> <button onclick="removeTodoItem()"><span id="counter"></span> Remove</button> ``` <b>Line 1-3:</b> The `<ul></ul>` tags establishes an unordered list which serves as placement for the todo list. <b>Line 5:</b> Establishes the `div` for control purposes (concludes on Line 19). <b>Line 6:</b> Establishes a text input box for the user to be able to type a value into the box. The text box included an event listener in the form `onEnterKey`. <b>Line 7:</b> Establishes an <i>add</i> button with the `onclick` event listener which works with the JS function `addToDoItem` for when the user clicks the button. <b>Line 8:</b> Establishes a <i>remove</i> button with the `onclick` event listener which works with the JS function `removeToDoItem` for when the user clicks the button. Furthermore, the button contains a span `counter` which tabulates the total number of todo items to remove. ::: <b>CSS:</b> :::success The CSS focuses on layout and appearance; the various codes have an affect on font size, padding, form of cursor, etc. We will not go into too much detail since it is mostly self-explanatory and not the primary focus of the functionality of the program. ::: <b>JavaScript:</b> :::success ```javascript= var data = [ { id: 1497141891479, task: "Wake up", done: false }, { id: 1497141913701, task: "Eat breakfast", done: false }, { id: 1497141937545, task: "Learn code", done: true } ]; ``` <b>Lines 1-17:</b> Var data consists of an array that, in this case, notes three (3) different tasks with their respective number `id` and their status (a Boolean). The task is visually displayed to the user via the todo list. ::: :::success ```javascript= var todosEl = document.querySelector('#todos'); var inputEl = document.querySelector('input'); var completedEl = document.querySelector('#counter'); ``` <b>Lines 1-3:</b> These lines note three distinct variables and employ `document.querySelector` as a value assigner based on what is stipulated in the code. Ultimately, `todosEl` connects with the id `todos`, `inputEl` relates to the text box input field, and `completedEl` works with the `counter` id. ::: :::success ```javascript= 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)">`; todosHTML += `<i class="fa fa-check-circle-o"></i>`; // Font-awesome } else { todosHTML += `<li id="task-${ todo.id }" onclick="toggleComplete(event)">`; 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(); } ``` <b>Lines 1-24:</b> Establishes the function `updateToDoItems`. In this block of text, we get to see the functionality of the program. Specfically, line 8 notes `if (todo.done)` informs of what will happen if an object's done value meets the condition of true. If so, lines 9-10 describe that the item will be checked through as completed (based on its class). Additionally, line 16 stipulates that any added item will appear on the todo list, which is closed on line 17 with the `li` tag. ::: :::success ```javascript= 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; } } function onEnterKey(event) { if (event.code === "Enter") { addTodoItem(); } } function validateTask(task) { if (task !== "") { return true; } else { return false; } } ``` <b>Lines 1-27:</b> This code blocks works with three different functions. The first function, `updateRemoveBtn` consists of a variable with an assigned value (Line 2) that indicates which items have been completd. Lines 8-13 function to establish whether the <i>remove</i>button will be active or disabled. The second function, `onEnterKey` works to signal to the `addTodoItem` if the user presses the <i>enter</i> key. Last, the `validateTask` function reads to see if the user has entered text into the input box and return a true or false statement. This not only serves the purpose of checking if information has been entered, but it also prevents empty items from being added to the list. ::: :::success ```javascript= function addTodoItem() { if (!validateTask(inputEl.value)) { return; } var newTodo = { id: getTimeStamp() }; newTodo.task = inputEl.value; newTodo.done = false; data.push(newTodo); updateTodoItems(); resetInput(); } ``` <b>Lines 1-17:</b> These lines are specific to the `addTodoItem` function. This function establishes whether the input field is empty, and if so, nothing should be done. It also creates a new variable `newTodo` (Line 6), which will have its own id based on the timestamp (Line 7). The last lines (15-16) of the block call specific functions: `updateTodoItems` and `resetInput`. ::: :::success ```javascript= function toggleComplete(event) { var todoID = parseInt(event.currentTarget.id.replace('task-','')); var todoData = getTodoData(todoID); todoData.done = !todoData.done; updateTodoItems(); } function removeTodoItem(event) { var incompleteTodos = data.filter(function(todo){ return todo.done === false; }); data = incompleteTodos; updateTodoItems(); } function resetInput() { inputEl.value = ""; } 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; } } if (todoFound) { return todoFound; } else { return null; } } ``` <b>Lines 1-36:</b> This code block establishes several functions: `toggleComplete` (Line 1), `removeTodoItem` (Line 8), `resetInput` (Line 16), and `getTodoData` (Line 20). `toggleComplete` consists of creating a `todoID` variable which is assigned to related id and chosen todo item; it is noted as `currentTarget` when clicked on. The `removeTodoItem` function consists of the `incompleteTodos`, which are filtered out if noted as false (Line 10). `resetInput` consists of reallocating any `inputEl` value to an empty input box. Last, `getTodoData` consists of creating the `todoFound` variable (Line 21) and a loop that checks for data related to the chosen id (Lines 23-29). The break (Line 27) serves as a stop if the noted todo has been chosen. Lines 31-36 are specific to no value for `todoFound` and returns a null value when that is the case. ::: **Make it yours (group's)** - 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? :::success This is a simple program with simple functionality that users can use easily to keep track of their tasks that they need to complete. Thus, we did not feel the need to make it more complex than necessary. However, we did want the list to be a little more lively so we added some color by making each <i>add</i> and <i>remove</i> button distinct, so that the <i>add</i> button is green and the <i>remove</i> button is red. Additonally, we relocated the `counter` so that the number of items removed would appear after the word <i>remove</i> for aesthetic and readability purposes. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully