Reputation: 35
I have an image-gallery like following
<div class="row gallery necklace">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery1" class="FirstImage" src="./images/gallery/jewellery1.jpg">
</div>
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery2" src="./images/gallery/jewellery2.jpg">
</div>
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery3" src="./images/gallery/jewellery3.jpg">
</div>
</div>
If an image is clicked I need to get its src (may be use alert() to show the src); how is this possible using jquery?
Upvotes: 0
Views: 35
Reputation: 115222
Bind click()
event handler, to get image source inside callback function use this.src
, this refers to the clicked dom object
$(document).ready(function() {
$('img').on('click', function() {
alert(this.src);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row gallery necklace">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery1" class="FirstImage" src="./images/gallery/jewellery1.jpg">
</div>
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery2" src="./images/gallery/jewellery2.jpg">
</div>
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery3" src="./images/gallery/jewellery3.jpg">
</div>
</div>
Upvotes: 0
Reputation: 8206
$('img').on('click', function() {});
targets the img
elements in the DOM and adds event function of click to them. you can get the attribute source using .attr('src')
and $(this)
targets the specific img that you clicked on to trigger the event function.
$(document).ready(function() {
$('img').on('click', function() {
src = $(this).attr('src');
alert(src);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row gallery necklace">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery1" class="FirstImage" src="./images/gallery/jewellery1.jpg">
</div>
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery2" src="./images/gallery/jewellery2.jpg">
</div>
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
<img id="jewellery3" src="./images/gallery/jewellery3.jpg">
</div>
</div>
Upvotes: 1