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
  • 160,666
  • 24
  • 190
  • 242
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
  • 160,666
  • 24
  • 190
  • 242