The DOM and jQuery


Goal

By the end of today, you will be able to:

  1. understand the jQuery wrapper function, $()
  2. use the jQuery wrapper for selecting, creating or modifying elements

Remember that jQuery is implemented using JavaScript, so there's nothing that jQuery does that you can't do in raw JavaScript.

Why jQuery over JavaScript?

  1. It's more concise.

  2. It handles browser inconsistencies and incompatibilities, so jQuery code is more likely to run correctly in all browsers.

  3. It does cool things like those animations that we have for removing quiz answers (list items). You can try it on the items below. We'll explain that code a bit later in the course. Here is a list of some other cool things that we'll also learn later.

Recap

In the readings, the most important points we want you to understand are:

  • The DOM is a bridge between the document and JavaScript. It presents a set of JavaScript objects with methods that allow JS to create elements, modify elements, and delete element.
  • jQuery is a popular JavaScript library that makes code to modify the document that is more concise, consistent and portable.
  • To use jQuery, you have to load the library. There are many ways; we're going to load it from Google.
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    

    A common mistake is to forget to load that, or to load it after your code that uses it.

  • Almost everything in jQuery works by selecting a set of elements and then operating on them using methods.
    $("set selector").meth1();
  • When operating on sets of existing things, that set selector is the same as the CSS language:
    $("nav a").css("text-decoration","none");
  • jQuery can also create elements by putting HTML code in the selector string:
    $("<a>").html("Search")
  • jQuery methods can be chained so you can do several things with the set of elements. For example, to add a link to the nav element, we can do this:
    $("<a>").html("Search").attr("href","http://www.google.com/").appendTo("nav");
  • Finally, we looked at hiding and showing elements, using the .hide() and .show() methods.

Quiz Question Nr. 1

Assume you have an HTML page with a lot of text, for example the lecture notes. What will the statement $("p") do?

  1. Return the first p element that it finds.

  2. Return a set of all p elements in the document.

  3. Create a new paragraph, unattached to the document.

  4. Create a new paragraph at the end of the body.

Quiz Question Nr. 2

Which of the following statements will add a new header element to the page?

  1.  $("h2").html("November").appendTo("body");
  2.  $("<h2>").html("November").appendTo("body");

What does the other one do?

Quiz Question Nr. 3

Using jQuery, how could we modify the SRC of an IMG whose ID is pic to be "percy.jpeg"

  1.  $("#pic").attr("src","percy.jpeg"); 
  2.  $("#pic").src("percy.jpeg"); 
  3.  $("#pic").html("<img src='percy.jpeg'>")
  4.  $("#pic").setSrc("percy.jpeg")

Quiz Question Nr. 4

Which of the following code excerpts will make an h1 element disappear?

  1. $("h1").attr("display","hidden"); 
  2. $("h1").display("none");
  3. $("h1").remove();
  4. $("h1").hide(); 

What's another way to make it disappear?

Quiz Question Nr. 5

Suppose there are 5 H2 elements on a web page, and we execute the following code:

$("h2").css("color","red");
  1. The first one turns red.
  2. The last one turns red.
  3. All of them turn red.
  4. An error is reported.

Quiz Question Nr. 6

jQuery's method chaining does what?

  1. Applies the same method to several objects
  2. Applies several methods to the same object(s)
  3. Appends an object to a list
  4. Adds an unattached object to the page

Quiz Question Nr. 7

What happens when the jQuery selector expression doesn't match any objects?

  1. You get an error message in the console.
  2. You get an alert indicating the error.
  3. You get a warning in the console
  4. None of the above. In fact, nothing happens.

Exercise 1

  1. Open up hp-chars.html in a separate page.
  2. Take a minute to view the source and get a sense of what the page has.
  3. Open up the JavaScript console. You'll do this entire exercise using the console.
  4. This page has jQuery loaded. Test this by typing both of the following variables in the console, to see what they contain:
          $
          jQuery
        
  5. Select the H1 element(s) to see what the result is:
    $("h1");
  6. Select the LI element(s) to see what the result is:
    $("li");
  7. Store the H1 element(s) in a variable, and then type the name of the variable and a dot, to see what kind of completions the Chrome Inspector offers you. These are the jQuery methods on that object.
          var h1 = $("h1");
          h1.
        
  8. Do the following operations on the h1 element:
    • Change the text to "J.K. Rowling's creations"
    • Change it to be 24px and in red.

Your solution might look like this:

$("h1").html("J.K. Rowling's creations");
$("h1").css("font-size","24px");
$("h1").css("color","red");
  

Alternatively, it might be:

$("h1").html("J.K. Rowling's creations").css("font-size","24px").css("color","red");
  

Or, more readably, this:

$("h1")
    .html("J.K. Rowling's creations")
    .css("font-size","24px")
    .css("color","red");
  

The latter two are equivalent, and preferable to the first because they are more efficient (though a few milli-seconds hardly matters for code like this).

Multi-line Input in Chrome Inspector

The Chrome Inspector is great in many ways, but one weakness is that it's hard to have multi-line input, even for something simple like this:

  function makeRed(sel) {
      $(sel).css("color","red");
  }

It's only three lines of code, but the Chrome Inspector will complain about a syntax error when you hit "enter" after the open brace.

There are two solutions:

  1. Put everything on one line, which is easy but ugly:
    function makeRed(sel) { $(sel).css("color","red");}
  2. Use Control+Enter instead of just Enter when you want a multi-line input. (Use regular Enter when you're done.)

Try typing in the makeRed function, using either technique, and then using it to make the H2 elements red.

Exercise 2

  1. Dynamically add the next Weasley, namely Percy, to the list in hp-chars.html.
  2. Define a function named addWeasley that takes one argument, the name of a Weasley child, and adds them to the appropriate list.
  3. Use your function to add Fred, George, Ron and Ginny.

Your solution might look like this:

$("<li>").html("Percy").appendTo("#list2");

function addWeasley(name) {
    $("<li>").html(name).appendTo("#list2");
}

addWeasley("Fred");
addWeasley("George");
addWeasley("Ron");
addWeasley("Ginny");
  

Exercise 3

Let's turn to the figure on the page.

  1. Write some jQuery code to show Hermione's picture (the relative URL is ../potterpics/hermione-granger-thumb.jpeg) instead of Harry's picture. It'll do that by changing value of the SRC attribute.
  2. Define a function name changePicthat takes one of these names as an argument:
    • draco-malfoy
    • harry-potter
    • hermione-granger
    • ron-weasley

    The function then changes the SRC of the image appropriately. It should also change the ALT and the FIGCAPTION text.

  3. Bonus points for a function that takes two arguments, first name and last name, and does the same thing but the text looks nicer.
  4. Use your function to change the picture.

Your solution might look like this:

function changePic(name) {
    $("#mainfig img")
        .attr("src","../potterpics/"+name+"-thumb.jpeg")
        .attr("alt",name);
    $("#mainfig figcaption").html(name);
}

changePic("ron-weasley");

With bonus:

$("#mainfig img")
    .attr("src","../potterpics/hermione-granger-thumb.jpeg")
    .attr("alt","Hermione Granger");
$("#mainfig figcaption").html("Hermione Granger");

function changePic(fname,lname) {
    var with_hyphen = fname + "-" + lname;
    var with_space  = fname + " " + lname;
    $("#mainfig img")
        .attr("src","../potterpics/"+with_hyphen+"-thumb.jpeg")
        .attr("alt",with_space);
    $("#mainfig figcaption").html(with_space);
}

changePic("ron","weasley");
  

Exercise 4

  • Use the .hide() method to make the figure disappear
  • Use the Chrome Inspector to check that the figure is still there, just not displayed.
  • Make it reappear using .show()
  • For fun, try .fadeOut() and .fadeIn().

Summary

We hope that after these activities you have a good understanding of:

  • the jQuery wrapper function, $()
  • using the .html() method to add content
  • using the .css() and .attr() methods to modify elements
  • using the hide() and show() methods

Solutions

Will be posted later, visit again after .

Quiz Questions:

    1. B
    2. B
    3. A
    4. D  another way is $("h1").css("display","none");
    5. C
    6. B
    7. D  I hate this feature of jQuery!