Giter VIP home page Giter VIP logo

jquery-dom's Introduction

General Assembly Logo

jQuery DOM Manipulation

Objectives

By the end of this lesson, students should be able to:

  • Diagram the DOM
  • Reference jQuery documentation when learning a new technique
  • After selecting a DOM node, reach another node using traversal
  • Get data from the DOM using jQuery
  • Put data into the DOM using jQuery

Preparation

  1. Fork and clone this repository. FAQ
  2. Create a new branch, training, for your work.
  3. Checkout to the training branch.
  4. Install dependencies with npm install.

The Document Object Model (DOM)

  • The DOM is a recursive tree.

The DOM is a (potentially) large object that describes the structure of our content. Since it's an object, we can use normal techniques to get and set data! In the browser, the DOM is represented by the document object. JS specifies some built-in methods that make using the DOM easier. Remember! The DOM is not the source code.

jQuery

  • The "query" in jQuery comes from SQL.
  • We can retrieve and put data into the DOM using jQuery.
  • jQuery uses selectors (css selectors, remember?)

Demo: Diagram the DOM

Demo translating a wireframe into a tree diagram.

Lab: Diagram the DOM

  1. Consultant: Give wireframe
  2. Developer: Draw a tree diagram
  3. Consultant: Draw the solution
  4. Discussion and questions

Code-Along: DOM Traversal

  • Deface the Jimmy Buffet
  • Add console snippet below to use jQuery.

var script = document.createElement('script');script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";document.getElementsByTagName('head')[0].appendChild(script);

Demo: jQuery Setters & Getters

When reading the jQuery documentation, be sure to scroll through the whole document to ensure you're looking at the correct method signature. Most jQuery methods change their behavior depending on the number of arguments they have when called.

For example, have a look at .val(). Note in the table of contents that there are two method signatures, .val() and .val(value). This is our hint that .val() can do two things.

Reading the documentation, we discover that .val() is getter on an element, but that .val(value) is a setter on an element. Be sure you're using the correct method. Reading examples is very helpful, and the jQuery examples in the docs are fully functional!

We can use .val() on the Jimmy Buffet page to get and set text in the search box.

Demo: DOM Events and Event Handlers

The DOM emits 'events' when users interact with the browser. Event handlers 'listen' for DOM events emitted from the DOM node they are 'attached' to, and run code when that event happens. Some common events that we might want to use event handlers on are 'click', 'hover', 'focus', or user keystrokes. Full list of DOM events

Lab: Register an Event Handler

Continue defacing the Jimmy Buffet. This time with an event handler.

Lab: Research Common jQuery Functions

Here is a list of most commonly used jQuery API functions:

  1. find()
  2. hide()
  3. show()
  4. html()
  5. append()
  6. prepend()
  7. on()
  8. off()
  9. css()
  10. attr()
  11. val()
  12. text()
  13. each()

Demo: event.target

Open the console in chrome and paste the following code in.

$("#toctitle").on('click', function(event){
  console.log("event is ", event);
});

How would we access specific attributes of that event? Try adding this code now as well:

$("#toctitle").on('click', function(event){
  console.log("event.target is ", event.target);
});
$("#toctitle").on('click', function(event){
  console.log("event.type is ", event.type);
});

Bubbling

When dealing with the DOM and click handlers, we're faced with a small problem that is simple to work-around if you know it exists. Bubbling occurs when an event takes place on a child element of the DOM that does not have an event handler of its own. In the scenario that this happens, the browser will search up the DOM chain until it finds an appropriate event handler.

In the example below we have a click handler registered on the

    with id="thisOne". However, if we were to click the 2nd
  • with <!--the innermost-->, it will still run our click handler.

    <html>
      <div>
        <ul> id="thisOne" class="d1">Title  <!-- the topmost --></ul>
          <li class="d2">1</li>
          <li class="d2">2</li>
          <li class="d3">3 <!-- the innermost --></li>
        </ul>
      </div>
    </html>
    $("#thisOne").on('click', function(){
      // do some stuff here
    });

    As a quick review, what would the DOM tree look like for the above html? Let's take 2 minutes and diagram it together. What would we do if the <li>s or the <ul> as a whole weren't present on time of page load, but we needed to add some event handlers for them?

    Best Practices

    • When attaching a click handler (or any handler), opt for the .on('click', function(){}) version over the .click(function(){}) verion. The reason is .on('click', ) accepts more arguments so we can be more specific with our handlers. See .click() vs. .on()

    Gotchas

    • Beware the difference between jQuery setters and getters.
    • Beware the difference between a jQuery collection and a jQuery object.
    • Beware the difference between .html(), .text(), and .val()
    • Beware treating jQuery objects as arrays. They aren't!
    • Beware attaching click handlers in a loop. It won't work, and it isn't necessary, because when you use .on('click') jQuery will attach the eventHandler on every single node in the jQuery object.

    Additional Resources

    License

    1. All content is licensed under a CC­BY­NC­SA 4.0 license.
    2. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].

jquery-dom's People

Contributors

bengitscode avatar jrhorn424 avatar micfin avatar payne-chris-r avatar realweeks avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-dom's Issues

Add Code along?

Comments about this repo/lesson mentioned it would be helpful to actually use some jQuery methods instead of just researching them/talking about them. I agree. Esp .on

Add a best practices list

Some things to include:

  • prefer .on('click') to .click()
  • prefer $.ajax() with the deferred object interface (don't use $.get and friends since it use arguments instead of "promise")

Change script injection snippet version and format

var script = document.createElement('script');script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";document.getElementsByTagName('head')[0].appendChild(script);

This is an in-line code block, and should be a fenced code block.

Also, the version should be updated.

Emphasize that source code is not the DOM

The DOM is an object the browser creates by reading source code.

Sometimes there is confusion about why changing something in the inspector doesn't persist between browser refreshes.

It's a good teachable moment about how browsers work (requests end with a response that has source, you can't edit a file on someone else's server can you? etc. etc.)

Bubbling section not necessary?

I don't think bubbling is a 'must have' but more of a 'nice to have'. It was added because of #19. Having just delivered it, I'm not so sure it should be covered.

Move this to ajax lesson?

  • Use $.ajax() over $.get(). The $.ajax version is preferable because
    of its use of promises which we'll cover later on in the course.

This is in the best practices section of the README, but this lesson is before the ajax lessons, so I don't think it makes much sense here.

Emphasize that jQuery does iteration for you

Trying to mix jQuery with JavaScript language features is, in general, a smell. The specific case where this bites people is:

  • Thinking a jQuery object is an array and has array methods (it has some, but not all)
  • Attaching a click handler in a loop fails (because, closure), but it's also not necessary, since if you use .on('click') instead of .click(), jQuery will attach the eventHandler on every single node in the jQuery object

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.