0

I have 3 images, each one with the same id/class (i have tried both) and on click i want to get the src of the image i click on, instead i get the src of the first image

I have tried using Id's, Classes, the img element, this. and nothing seems to work

Theres more code in the parents of the element, but its all for appearnce

HTML


<img src="_IMAGE_SRC_" class="card-img-top img-fluid webImg"/>
<img src="_IMAGE_SRC_" class="card-img-top img-fluid webImg"/>
<img src="_IMAGE_SRC_" class="card-img-top img-fluid webImg"/>

JavaScript

$('.webImg').on('click', () =>{
    let imgSrc = $(".webImg").attr('src')

    console.log(imgSrc);

})

I have multiple images, and i want to get the image src so that when i click on it, a model comes up, i then use the variable to populate the image inside the modal

j_velaz
  • 11
  • 5

3 Answers3

1

The problem is that this line let imgSrc = $(".webImg").attr('src') re-queries the DOM for the .webImg elements, completely ignoring the one that was clicked. To find out which one was clicked, either use the passed in Event Object, or just use this which will be equal to the current element.

$('.webImg').on('click', function(e) {
    let imgSrc = $(e.target).attr('src')
    //or
    //let imgSrc = $(this).attr('src')

    console.log(imgSrc);

})

As @Taplar pointed out, in order to use the this option you'd have to change from an arrow function to a regular function.

You definitely want to use classes as opposed to id's, as id's are supposed to be unique and multiple elements on the page should not have the same id. This can cause issues when trying to grab the elements with JavaScript.

yts
  • 1,890
  • 1
  • 14
  • 24
0
$('.webImg').on('click', (e) => {
    console.log(
        e.target.src, //property access
        e.target.getAttribute('src'), //attribute access
        $(e.target).prop('src'), //jQuery property access
        $(e.target).attr('src') //jQuery attribute access
    );
})

You can pass in the event and grab the src off of the target either with the property or with the getAttribute method.

Taplar
  • 24,788
  • 4
  • 22
  • 35
0
$('.webImg').on('click', function(){
    let imgSrc = $(this).attr('src');
    alert(imgSrc);
});

IF you want to use imgSrc outside this function, declare it before, like let imgSrc = false;

Beneris
  • 627
  • 4
  • 11
  • So, after testing different things, i noticed that using the new ES6 function declaration, returns undefined... any clue why that would be? – j_velaz May 16 '19 at 19:44
  • @j_velaz https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable – Taplar May 16 '19 at 21:59