What is this "this" thing?

See more about:

Suppose we have a page with lots of images on it, like this one. Open it, and try clicking on the dogs, in any order you like. They’ll be highlighted.

How would you write the code for the page? One way is to give each dog an id:

<p>
  <img src="1.png" id="dog1" alt="Dog">
  <img src="2.png" id="dog2" alt="Dog">
  <img src="3.png" id="dog3" alt="Dog">
  <img src="4.png" id="dog4" alt="Dog">
</p>

There are 16 dogs on the page. So that would be 16 image tags with 16 ids.

What would the jQuery look like? Here is one option:

<script type="text/javascript">
  $(document).ready(function() {
    $("#dog1").click(function(){
      $("#dog1").addClass("selected");
    });
    $("#dog2").click(function(){
      $("#dog2").addClass("selected");
    });
    $("#dog3").click(function(){
      $("#dog3").addClass("selected");
    });
...
  });
</script>

The selected class has those funky borders.

This would work, but there are 16 dogs! That means 16 copies of the same code! Ack!

It’d be better if we could say to jQuery:

“Hey, jQuery! What up, dog? Add the selected class to the thing that was clicked on, whichever thing it was.”

Can we do this? Yes, we can!

First, let’s kill all the ids in the HTML.

<p>
  <img src="1.png" alt="Dog">
  <img src="2.png" alt="Dog">
  <img src="3.png" alt="Dog">
  <img src="4.png" alt="Dog">
</p>

Here’s the jQuery:

<script type="text/javascript">
  $(document).ready(function() {
    $("img").click(function(){
      $(this).addClass("selected");
    });
  });
</script>

Line 3 gives a click function for img. There are 16 img tags on the page. So, click on any of the 16 images, and this function runs.

The magic is in line 4:

$(this).addClass("selected");

this is whatever $("img") matched. So if the user clicked on the first image, this would be the first image. If the user clicked on the tenth image, this would be tenth image.

W00f! One function replaces 16! Hooray for this!


Lessons

How to...


Dogs