SampleJS

by abds040

HTML

<!--script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.core.min.js"></script-->
<h3>
Sample JS (Vanilla)
</h3>

<input type="text">
<button>Add Todo</button>

<ul></ul>

<script>
	
var inputEl = document.querySelector('input');
var buttonEl = document.querySelector('button');
var ulEl = document.querySelector('ul');

var todos = [];

buttonEl.addEventListener('click', addTodo);

function addTodo() {
	var userInput = inputEl.value;
  if (userInput.trim() == '') {
  	return;
  }
  // The new JavaScript object (id will not always be random)
  var newTodo = { id: Math.random(), value: userInput }; 
  // Lodash adds a unique ID
  //var newTodo = { id: _.uniqueId(), value: userInput };
  todos.push(newTodo);
	var todoLi = document.createElement('LI');
  todoLi.textContent = userInput;
  todoLi.addEventListener('click', removeTodo);
  todoLi.dataset.id = newTodo.id;
  ulEl.appendChild(todoLi);
  console.log(todos);
}

function removeTodo(event) {
	var clickedLi = event.target;
  for (var i = 0; i < todos.length; i++) {
  	if (todos[i].id == clickedLi.dataset.id) {
    	todos.splice(i, 1);
      break;
    }
  }
  clickedLi.parentNode.removeChild(clickedLi);
    console.log(todos);
}
</script>