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?
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.
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.
$(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.
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.
Try:
$('a.yourClassName').click(function(){
$('img#'+ this.id).show();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With