I want to attach event listener to all img-frame classes and I get which element (by index) inside the parent has been clicked:
$('.img-frame').each((i, img) => {
$(img).on('click', pictureClicked);
});
function pictureClicked(e) {
console.log(e.currentTarget)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="three-image-container">
<img class="img-frame" src="blob:https://localhost:4000/daf31145-292d-462c-bc94-aad0610b2972">
<img class="img-frame" src="blob:https://localhost:4000/8e4a143e-f9f0-47ec-a361-4e571bb49d1a">
<img class="img-frame" src="blob:https://localhost:4000/c8236624-571d-4386-9225-e14e7fac9560">
</div>
So if the first one has been clicked I want 0 and ...
How can I do this?
CodePudding user response:
You want to delegate the event to save on handlers:
$('.three-image-container').on('click', 'img', pictureClicked);
function pictureClicked(e) {
console.log($(e.target).index())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="three-image-container">
<img class="img-frame" src="blob:https://localhost:4000/daf31145-292d-462c-bc94-aad0610b2972">
<img class="img-frame" src="blob:https://localhost:4000/8e4a143e-f9f0-47ec-a361-4e571bb49d1a">
<img class="img-frame" src="blob:https://localhost:4000/c8236624-571d-4386-9225-e14e7fac9560">
</div>
CodePudding user response:
I think it should help you :)
$('.img-frame').each((i, img) => {
$(img).on('click', pictureClicked);
});
function pictureClicked(e) {
console.log($(e.currentTarget).index())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="three-image-container">
<img class="img-frame" src="blob:https://localhost:4000/daf31145-292d-462c-bc94-aad0610b2972">
<img class="img-frame" src="blob:https://localhost:4000/8e4a143e-f9f0-47ec-a361-4e571bb49d1a">
<img class="img-frame" src="blob:https://localhost:4000/c8236624-571d-4386-9225-e14e7fac9560">
</div>