0

I am trying to get the img src for a javascript function.

But the images were set true a foreach loop and the src of the image are send from the model like this

@{
     foreach (var image in Model.ImagesInFile)
     {
         var imageFile = "/Content/images/" + image;
         <div class="image_holder">
             <img id="img_tumb" class="images_display" src="@imageFile" alt="testimage" onclick="show_pic()" />
         </div>         
     }
 }

What I'm trying to do is when I click on an image that image should be displayed with javascript in a div that I have,

<div class="image_showcase" id="img_show">

</div>

But how do get the source of the image that is clicked ??

I tried this,

<script>
    function show_pic() {
        if ($('#img_show').find('img').length > 0) {
            alert("same image");
        } else {
            var img_src = document.getElementById('img_tumb').src;
            var img = document.createElement("img");
            img.src = img_src;
            document.getElementById('img_show').appendChild(img);
        }       
    }
</script>

But when I click on any image I will always get the first image in the list, it doesn't matter what image I clicked !?

yajiv
  • 2,901
  • 2
  • 15
  • 25
scg
  • 21
  • 9
  • Use the JS `event` object, which has a `target` property, to get the image that was clicked. –  Mar 08 '18 at 20:25
  • @Amy Thanks, that's the solution! – scg Mar 08 '18 at 20:43
  • No problem. The answer below is correct in one respect: it's invalid to have more than one element in an HTML document with the same ID. So, be sure to give your image elements unique IDs (if they need IDs at all). –  Mar 08 '18 at 20:45

1 Answers1

0

Looks like you assign same id for all your images.

Don't forget to pass the id as function parameter.

@{
    var count = 0
    foreach (var image in Model.ImagesInFile) {
        count ++
        var id = "img_tumb" + count
        var imageFile = "/Content/images/" + image;
        <div class="image_holder">
            <img id="@id" class="images_display" src="@imageFile" alt="testimage" onclick="show_pic(@id)" />
        </div>
    }
}

<script>
    function show_pic(id) {
        if ($('#img_show').find('img').length > 0) {
            alert("same image");
        } else {
            var img_src = document.getElementById(id).src;
            var img = document.createElement("img");
            img.src = img_src;
            document.getElementById('img_show').appendChild(img);
        }       
    }
</script>
sultan
  • 4,543
  • 2
  • 24
  • 32