JQuery click listener for class

javascript, jquery

Solution

You shouldn't use the ids of `a` tags to define their target. Better use the `href` attribute instead:

<img id="img1" ...>
<img id="img2" ...>
<a href="#img1" class="image-link">Click me</a>
<a href="#img2" class="image-link">Click me</a>

jQuery("a.image-link").click(function(){
  $(this.href).show();
});

This allows you to have two links for the same image.

Problem

I have a class of images in HTML, with IDs `img1`,`img2`,...,`img9`. I want to make links (HTML `a` tag) with IDs `link_img1`, `link_img2`, ..., `link_img9` so that whenever I click on a link, the corresponding image appears. I'm thinking about assigning all the links to the same class, then add a JQuery click listener for that class, and inside the listener, look for the ID of that link, and shows the corresponding image. How do I add a JQuery listener for a class, and how do I get the ID from the element?

Original source