javascripthtmlimagemodal-dialogon-the-fly

Change image source inner modal on the fly


I am trying to change the source image of an image HTML element <img src="/some/dynamic/path"></img>.

How I take the this.id is very complex and is outside the context of this question, but suffice to know that it is obtained by PHP and at the time of click, on a list item (not showed here), the identifier is already set and ready for use. The console.log ensures that.

The problem is that when I click on the element, the modal appears to me, but I do not see the image. By debugging on the browser I noticed that the src field is always empty.

I suppose the cause of the problem is to be found in the Javascript code I posted. In particular, the execution of the two instructions is somewhat asynchronous.

What do you think about it? Do you need further details?


The modal code:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-body text-center">
                <img id="modalImage" src="">
            </div>
        </div>
    </div>
</div>


And the JS code:

$(".listShowCard").click(function() {
    console.log("/images/cards/"+this.id+".png");
    $("#modalImage").src="/images/cards/"+this.id+".png";
    $("#myModal").modal('show');
});

Solution

  • use:

    document.getElementById('modalImage').src=`/images/cards/${this.id}.png`;
    

    When you're using elements with IDs, try to avoid jQuery, since the call is so much slower than pure JS call.