Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery click listener for class

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?

like image 619
Mika H. Avatar asked Mar 16 '13 18:03

Mika H.


People also ask

Can you add event listener to class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

What is $( this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.


2 Answers

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.

like image 73
jantimon Avatar answered Sep 28 '22 18:09

jantimon


Try:

$('a.yourClassName').click(function(){
   $('img#'+ this.id).show();         
});
like image 39
Anujith Avatar answered Sep 28 '22 17:09

Anujith