How to change image src using jquery

You are currently viewing How to change image src using jquery

How to change image src using jquery

To change the image src using jQuery, the simplest way is to use the jQuery attr() method. You might want to display a different image to the user, maybe if they click a button or perform another action so here is a quick example of how to change image src using jQuery


how to change image src using jquery.

html:

<div id="image-div">
    <img src="https://wptech.fun/img/test-img.jpg" id="picture" >
</div>

js:

jQuery('#picture').attr('src', 'https://wptech.fun/img/new-img.jpg');

The above code will change the image src attribute to “img/new-img.jpg” as soon as the document has loaded. Of course, you probably don’t want to change the image immediately when the page loads.

So here is a quick example Changing the image on the click of a button.

html:

<div id="image-div">
<img src="https://wptech.fun/img/test-img.jpg" id="picture">
<button type="type" class="btn">Get & Set image src</button>
</div>

js:

jQuery('.btn').click(function(){   var imgsrc = 'https://wptech.fun/img/new-img.jpg';
   jQuery('#picture').attr('src', imgsrc);
});

Hopefully this article has helped you understand how you can update the image source (src) using jQuery. if you have any questions you can contact us and read more articles from wptip.in

if you need any help in wordpress development click here

Leave a Reply