acbrent25
9/4/2017 - 4:18 PM

jQuery Todo List App

jQuery Todo List App

<!DOCTYPE html>

<html lang="en-us">

  <head>

    <meta charset="UTF-8">
    <title>Todo</title>

    <style>

      body {
        background: cornflowerblue;
        color:yellow;
        text-align: center;
      }

      h1 {
        font-size: 42px;
      }

      input {
        width:50%;
        margin:10% 2%;
        height:32px;
        font-size: 24px;
      }

      button { height: 32px; }

      #tasks {
        background-color: antiquewhite;
        width:60%;
        height:400px;
        overflow: auto;
        margin: 0 auto;
        color:black;
      }

      #tasks div {
        border:1px solid grey;
        margin: 2%;
        font-size: 32px;
        padding:5%;
        box-sizing: border-box;
      }

      #delete {
        cursor:pointer;
        float:right;
        color:red;
        font-weight: bold;
      }

    </style>

  </head>

  <body>

    <h1>Todo List</h1>
    <input id="new-task" type="text">
    <button id="add">Add!</button>
    <div id="tasks"></div>

    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <!-- Script -->
    <script src="app.js"></script>

  </body>

</html>
// jQuery TODO: SOLUTION

// When the user clicks any button, run addTask.
$("button").click(addTask);

// Add a listener to the document.
// It should keep an ear out for a click on elements with an id of "delete".
// We can't use .click, because the element is dynamically created.
$(document).on("click", "#delete", removeTask);

// When a user presses any key on their keyboard,
$("input").keypress(function(event) {

  // listen to see that key was "enter."
  if (event.which === 13) {

    // If so, run addTask.
    addTask();
  }
});

// Function to add a task.
function addTask() {

  // Get the content (value) of the input box.
  var task = $("#new-task").val();

  // Append that content to the #tasks div.
  // Nest our content in another div in another div
  // with a span containing an X.
  // Notice the id? We can delete the task whenever the user clicks the span.
  $("#tasks").append("<div>" + task + "<span id='delete'>X</span></div>");

  // Clear the content of the input box.
  $("#new-task").val("");
}

// Function to remove a task.
function removeTask() {

  // Grab the closest div to the element that was clicked and remove it.
  // (In this case, the closest element is the one that's encapsulating it.)
  $(this).closest("div").remove();
}