Reputation: 65
I have a set of images and I'm trying to use jQuery to retrieve the img src of any image clicked. The problem is that my current code doesn't console.log() anything and when trying to manipulate it through the console it shows me undefined. Please I am not too familiar with jQuery(or javascript in general) and I'm very open to vanilla js solutions too.
HTML
<div class="row">
<div class="col-sm-6 p-3 col-lg-3 img">
<img src="static/test-1.jpg" alt="">
</div>
<div class="col-sm-6 p-3 col-lg-3">
<img src="static/test-2.jpg" alt="">
</div>
</div>
JavaScript
$('img').click(function() {
var $thumb = $('this');
console.log($thumb.attr('src'));
});
Upvotes: 0
Views: 194
Reputation: 1527
This should do it.
$("img").on("click", function() {
var $thumb = $(this);
console.log($thumb.attr("src"));
});
Your problem is that $("this") looks for an HTML tag called <this> due to the quotes that are around it. Without the surrounding quotes it just wraps the object called "this" in a jQuery object. And since the event handler is attached to images, "this" refers to the image that was clicked.
Without jQuery:
for (var images = document.getElementsByTagName("img"), i=0; i<images.length; i++) {
images[i].addEventListener("click", function() {
console.log(this.src);
})
}
Upvotes: 4
Reputation: 3196
Here is a simple way.
Without extracting too much away from your original code you can target the current element by simply using this
explicitly.
Since $('img').click
is already targeting the img
element you can do an immediate reference like so:
this.src
Same result, less code.
$('img').click(function() {
console.log(this.src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-6 p-3 col-lg-3 img">
<img src="https://cdn.pixabay.com/photo/2020/01/01/18/51/bottle-of-sparkling-wine-4734176__340.jpg" alt="">
</div>
<div class="col-sm-6 p-3 col-lg-3">
<img src="https://cdn.pixabay.com/photo/2020/12/05/10/31/woman-5805574__340.jpg" alt="">
</div>
</div>
Upvotes: 1