JavaScript


with jQuery

http://seattlejs.training.formidablelabs.com

@FormidableLabs | formidablelabs.com

Tip - space bar advances slides

jQuery

jQuery is an enormously popular library for HTML / DOM manipulation, event handling, effects, and data.


Helps your HTML do stuff... more easily

jQuery Parts

Further Reading

Starter Project

todo.html


                <html>
                  <head>
                    <style>li { cursor: pointer } .complete { text-decoration: line-through; }</style>
                    <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.underscore.min.js"></script>
                    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <script src="todo.js"></script>
                  </head>
                  <body>
                    <div id="todo-items">
                      <h2>To Dos</h2>
                      <ul></ul>
                    </div>
                  </body>
                </html>

Let's Try It Out!

We start here (todo.html) ...

... and end here (todo-done.html)!

We Will

  • Get todo item data
  • Create DOM elements from data
  • Bind UI actions
  • ... and we can organize away!

AJAX

AJAX lets you get data from a server without refreshing a page. Usually as JSON.

jQuery provides great support with the low-level $.ajax() and other helpers.

AJAX (GitHub) Demo


                // Get organization GitHub information.
                $.ajax({
                  url: "https://api.github.com/orgs/formidablelabs",
                  success: function (obj) {
                    console.log("Home:", obj.location, "Data:", obj);
                  },
                  error: function (xhr, status, error) {
                    console.log("OH NOES", status, error);
                  }
                });
                

AJAX (Alternate) Demo


                $.ajax("https://api.github.com/orgs/formidablelabs")
                  .done(function (obj) {
                    console.log("Home:", obj.location, "Data:", obj);
                  })
                  .fail(function (xhr, status, error) {
                    console.log("OH NOES", status, error);
                  });
                  

Some Todo Data

{
  "0": "walk the cat",
  "1": "grocery: emu burgers",
  "2": "cleaners: clown suit"
}

AJAX (Task)

// Get todo data for our app.
$.ajax({
 url: "http://seattlejs.training.formidablelabs.com" +
      "/topics/workshop/javascript/todos/data.json",
 dataType: "jsonp"
  // (1) LOG OUT TO CONSOLE
  // (2) PASS TO `addTodos`
});

AJAX Demo


                $.ajax({
                  url: "http://seattlejs.training.formidablelabs.com" +
                       "/topics/workshop/javascript/todos/data.json",
                  dataType: "jsonp",
                  success: function (data) {
                    console.log("Todos:", JSON.stringify(data, null, 2));
                    // addTodos(data);
                  }
                });
                

Selectors

jQuery allows you to use CSS-style Selectors to match and manipulate DOM elements.

Selectors Demo


                console.log("Body Element", $("body"));
                
                // How about PINK? [TRY: switch `children` to `find`]
                $("body").children("div").css({ background: "deeppink" });
                
                // Let's retitle.
                $("header > h2")
                  .css({ color: "white" })
                  .text("Unicorns are AWESOME!");
                  

Create Elements Demo


                // Create an element
                var $el = $("

Rainbows!

"); // Style it. $el.css({ color: "lightpink", "font-size": "24px" }); // Add it to the DOM. [TRY] $("#cm-output").append($el) $el.appendTo($("#cm-output"));

Clone Elements Demo


                // Create an element.
                var $el1 = $("

Puppies!

") .css({ color: "lightgreen", "font-size": "24px" }); // Clone it and change it. var $el2 = $el1.clone() .css({ color: "lightsalmon" }); $("#cm-output").append($el1, $el2); // Remove the first puppy or all of them. // [TRY] $el1.remove(); // [TRY] $("#cm-output").empty();

Selector API

  • Expressions: parent > child, .class, #id, :hidden
  • Traversing: find, children, closest
  • Manipulation: addClass, append, attr, css, text, html, remove, empty, clone, detach

Add Elements (Task)

// Create a single todo HTML
var createTodo = function (todo) {
  // TASK: Create DOM elements around a todo data item.
  // HINT: Create and return `
  • TEXT
  • ` elements. }; // Iterate todo data and create HTML for each. var addTodos = function (todos) { // TASK: Take todo data items, and create list items with `createTodo`. // HINT: "#todo-items ul" to select the base list. console.log("addTodos data: ", todos); };

    Add Elements Demo

    
                    // Create a single todo HTML
                    var createTodo = function (todo) {
                      return $("
  • " + todo + "
  • "); }; // Iterate todo data and create HTML for each. var addTodos = function (todos) { var $todosList = $("#todo-items ul"); _.each(todos, function (todo) { var $todo = createTodo(todo); $todo.appendTo($todosList); }); }; // BOOTSTRAP $("
    ").attr("id", "todo-items").append($("
      ")) .appendTo($("#cm-output")); $(function () { $.ajax({ url: "/topics/workshop/javascript/todos/data.json", dataType: "jsonp", success: addTodos }); });

      Events

      jQuery allows you to listen to and trigger events on DOM elements.

      Events Demo

      
                      // Listen to clicks!
                      $("h2").on("click", function (ev) {
                        // [TRY: event bubbling] ev.stopPropagation();
                        // [NOTE: If `a` or `submit`] ev.preventDefault();
                        $("h2").css({ color: "orangered", background: "lime" });
                      });
                      
                      // Targets: The element you actually clicked.
                      $("body").on("click", function (ev) {
                        console.log("CLICK", $(ev.target)[0].tagName, $(ev.target));
                      });
                      
                      // [TRY: Trigger] $("h2").click();

      Event API

      The same name can both listen OR trigger depending on function parameters.

      • Listen: on, change|click|hover
      • Trigger: trigger, change|click|hover

      Cross Off Todos (Task)

      // Change "complete" OR "unfinished" status.
      var changeTodo = function (ev) {
        // HINT: Remember `ev.target`
        // HINT: We have a `complete` CSS class to strike through.
        // HINT: See https://api.jquery.com/toggleClass/
        // HINT: In `addTodos` add a `click` handler to call `changeTodo`.
      };
      

      Cross Off Todos Demo

      
                      /*global createTodo:true */
                      var changeTodo = function (ev) {
                        $(ev.target).toggleClass("complete");
                      };
                      
                      var addTodos = function (todos) {
                        var $todosList = $("#todo-items ul");
                        _.each(todos, function (todo) {
                          var $todo = createTodo(todo);
                          $todo.appendTo($todosList);
                          
                          $todo.click(changeTodo); // [NEW] Add click handler.
                        });
                      };
                      
                      
                      
                      
                      
                      
                      
                      // BOOTSTRAP
                      function createTodo(todo) { return $("
    • " + todo + "
    • "); } $("head").append(""); $("
      ").attr("id", "todo-items").append($("
        ")) .appendTo($("#cm-output")); $(function () { $.ajax({ url: "/topics/workshop/javascript/todos/data.json", dataType: "jsonp", success: addTodos }); });

        Todo Enhancements

        • Create a new task from an input.
        • Delete task from a button or checkbox.
        • Edit task text with an input.
        • Filter tasks with an input query field and :contains() selector.

        jQuery

        @FormidableLabs | formidablelabs.com