samuel toh
samuel toh

Reputation: 7076

How can I replace image with javascript?

My view like this :

<li id="thumbnail-view" class="count-photo">
    <div class="thumbnail">
        <img src="{{ asset('img/thumbs/'.$photo) }}" alt="">
        <a href="javascript:" class="thumbnail-check"><span class="fa fa-check-circle"></span></a>
        <ul class="list-inline list-edit">
            ...
        </ul>
    </div>
</li>

My javascript like this :

var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

Upvotes: 2

Views: 4496

Answers (3)

Cloud
Cloud

Reputation: 1034

You should use like this: $('#thumbnail-view img').attr('src','path/to/photo');

Upvotes: 1

MrCode
MrCode

Reputation: 64526

Don't set the inner HTML of an image, set its src property.

$('#thumbnail-view img').prop("src", "{{ asset('img/thumbs/') }}"+photo);

Sidenote: if this is in a .js file then your template engine probably will not process the asset tag so you need to hardcode the path or grab it from elsewhere.

$('#thumbnail-view img').prop("src", "/assets/img/thumbs/"+photo);

Upvotes: 3

Janen R
Janen R

Reputation: 749

Simple way

 var photo = 'flower.jpg';
 $('#thumbnail-view img').attr('src', photo);

Upvotes: 5

Related Questions