Created
November 12, 2020 15:06
-
-
Save cferdinandi/0d2418e314f75b4e5b73d64401347d49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>React Todos in Vanilla JS</title> | |
| <style type="text/css"> | |
| body { | |
| margin: 0 auto; | |
| max-width: 40em; | |
| width: 88%; | |
| } | |
| label, | |
| input { | |
| display: block; | |
| } | |
| input { | |
| margin-bottom: 1em; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>React Todos in Vanilla JS</h1> | |
| <ul id="todo-list"></ul> | |
| <form id="add-todos"> | |
| <label for="new-todo">What needs to be done?</label> | |
| <input id="new-todo"> | |
| <button> | |
| Add #<span id="add-count">1</span> | |
| </button> | |
| </form> | |
| <script> | |
| // | |
| // Variables | |
| // | |
| var todoList = document.querySelector('#todo-list'); | |
| var addTodos = document.querySelector('#add-todos'); | |
| var addCount = document.querySelector('#add-count'); | |
| // | |
| // Methods | |
| // | |
| /** | |
| * Inject todo item into the UI | |
| * @param {String} todo Todo item text | |
| */ | |
| var injectTodo = function (todo) { | |
| var li = document.createElement('li'); | |
| li.textContent = todo; | |
| li.id = new Date().getTime(); | |
| todoList.appendChild(li); | |
| addCount.textContent = todoList.children.length + 1; | |
| }; | |
| /** | |
| * Handle submit events | |
| * @param {Event} event The event object | |
| */ | |
| var submitHandler = function (event) { | |
| // Stop the form from reloading the page | |
| event.preventDefault(); | |
| // Get the todo item field | |
| var text = addTodos.elements['new-todo']; | |
| // If there's no text in the field, do nothing | |
| if (!text || !text.value.length) return; | |
| // Inject the todo item into the UI | |
| injectTodo(text.value); | |
| // Clear the field | |
| text.value = ''; | |
| }; | |
| // | |
| // Event Listeners | |
| // | |
| // Listen for form submissions | |
| addTodos.addEventListener('submit', submitHandler); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment