Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jQuery: test for whether user clicks on an image

I'm playing around with building a more functional lightbox than the one created in jQuery basics and I'm struggling to find a test for whether a user clicks on an image or on the overlay surrounding the image. This is what I have so far,

//On click of the overlay
$("#overlay").not("img").click(function(e) {
  //If user clicks the image
  if (e.target === something to do with img) {
    //Move to the next imageIndex or if last image move to first imageIndex
    if (imageIndex !== imageTotal) {
      imageIndex += 1;
    } else {
      imageIndex = 0;
    }
    //Update the img src attribute
    var imageLocation = $("#imageGallery a").get(imageIndex);
    $image.attr("src", imageLocation);
  } else {
    //Hide the overlay
    $overlay.hide();
  }
});

e.target is this object:

<img src="http://www.example.com/example.jpg">

however, the src attribute will be different depending on which image is in the overlay.

I want to know whether there is an easy way to test whether the object is an img tag.

1 Answer

Yes! You can check to see if the target of the click was an img tag.

$overlay.click(function(e) {
  if ($(e.target).is('img')) {
    e.preventDefault(); 
    // All the other stuff you want to do...
  } else {
    $overlay.hide();
  }
});

This was an interesting expansion idea, so I took a shot at it for fun. I got hung up for a little while on one problem trying to work out a tricky selector, so I'd be interested to see what your solution is. Happy coding!

Thanks. I eventually found a solution, but your solution is much more elegant.