markberning
1/8/2018 - 6:24 AM

Make an HTML button run JavaScript

// 1. We want to get access to the display todos button.
// 2. We want to run displayTodos method when someone clicks the display todos button.

// Make sure your js script is loaded at the end of the html just before the closing <body> tag
// Give the button an id
<button id="displayTodosButton">Display Todos</button>

// Use document.getElementById('displayTodosButton') to get button and place in var
var displayTodosButton = document.getElementById('displayTodosButton');

// Add an event listener to the button for a click
// displayTodosButton.addEventListener('click', function(){});
displayTodosButton.addEventListener('click', function(){
  todoList.displayTodos();
});

//---------------------------------------------------------------
// Refactor to reduce amount of code
// change buttons from:
<button id="displayTodosButton">Display Todos</button>
<button id="toggleAllButton">Toggle All</button>
// to this:
<button onclick="handlers.displayTodos()">Display Todos</button>
<button onclick="handlers.toggleAll()">Toggle All</button>

// and then create an new object for the handlers to keep them organized
var handlers = {
  displayTodos: function(){
    todoList.displayTodos();
  },
  toggleAll: function(){
    todoList.toggleAll();
  }
};
// don't need all of the other code

//-----------------------------------------------------------
// Button and Text Field: get value from text field when clicking button
<button onclick="handlers.addTodo()">Add Todo</button>
<input type="text" id="addTodoTextInput">
// This will run the addTodo() function in the handlers object when clicked
// The id of the input field allows us to use getElementById in the js file.
addTodo: function(){
    var addTodoTextInput = document.getElementById('addTodoTextInput');
    todoList.addTodo(addTodoTextInput.value);
    addTodoTextInput.value = '';
  }
//