2

I need to get the source src URL from image clicked as HTML below:

$(document).ready(function() {
  $(".thumbnail").click(function() {
    var var1 = $(this).find('.thumbnail img').attr('src');
    console.log(var1);
    $('#main_image').attr('src', var1).load(function() {});
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="thumbnail">
<img src="http://www.euroe-com.com/agv/graphics/agv_0041A2HY-002_b.jpg" width="200">
<img src="http://www.euroe-com.com/agv/graphics/agv_0041A2HY-006_b.jpg" width="200">
<span>

<br /><br /><br />
Put inside this 
<img id="main_image" src="http://www.euroe-com.com/agv/graphics/added-desc/agv_0041A2HY-02211_415x500.jpg" width="400">

I tried the jQuery code as you see posted.

For some reason it throws undefined.

Here is in action http://jsfiddle.net/1oaxue9h

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Mistereri
  • 23
  • 2

1 Answers1

2

For some reason, even when the Tidy button is provided, people are lazy to tidy their codes.

Learn jQuery. You need to remove the .thumbnail from the selector to work. Coz, you are already here, which is denoted by this. Since, this is .thumbnail, just find("img") is enough.

var var1 = $(this).attr('src');

You also have an unclosed <span>, which needs to be changed as </span>.

$(document).ready(function() {
  $(".thumbnail img").click(function() {
    var var1 = $(this).attr('src');
    console.log(var1);
    $('#main_image').attr('src', var1).load(function() {});
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="thumbnail">
  <img src="http://www.euroe-com.com/agv/graphics/agv_0041A2HY-002_b.jpg" width="200">
  <img src="http://www.euroe-com.com/agv/graphics/agv_0041A2HY-006_b.jpg" width="200">
</span>

<br /><br /><br />
Put inside this 
<img id="main_image" src="http://www.euroe-com.com/agv/graphics/added-desc/agv_0041A2HY-02211_415x500.jpg" width="400">
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • hi Praveen, you are right, one thing though, if you test the modified code you provided, when is clicked on the Red image, still appears the black one. Please see it once more from your side. Thank You a lot – Mistereri Dec 22 '16 at 23:59
  • @Mistereri Try once more... I changed. Refresh the page. – Praveen Kumar Purushothaman Dec 22 '16 at 23:59
  • you are great man. It was so simple and neat solution. I lost a full day to find it by my self so I gave up and wrote it here. Very much appreciated. – Mistereri Dec 23 '16 at 00:05
  • 1
    I did it Praveen, sorry it was my first time i have posted here. happy holidays. – Mistereri Dec 23 '16 at 00:47