Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery change the value of an <img src="" by ID

I need some simple JQuery code so I can change the src value of a specific img.

It's currently:

<img id="myImage" src="image1.gif" />

and I need to change it to:

<img id="myImage" src="image2.gif" />

using JQuery.

like image 973
Satch3000 Avatar asked Jan 28 '12 15:01

Satch3000


People also ask

How can I change the IMG src?

To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.

Can JavaScript change the src attribute value of an IMG tag?

Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.

Can we change image src using JavaScript?

The cool thing about JavaScript is that you can use it to programmatically alter the DOM. This includes the ability to change an image's src attribute to a new value, allowing you to change the image being loaded.

How can I get image src value?

JavaScript code to get the HTML img tag src attribute valuevar img_src = document. getElementById("my-img"). src; console. log(img_src);


2 Answers

Using: $(function(){ ... });

You can use:

$('#id').attr('src', 'newImage.jpg');

to change the image source immediately.


Alternatively, you can use jQuery animations to change an image.

JS

$("#id1").fadeOut();
$("#id2").delay(200).fadeIn();

HTML

<div>
    <img id='id1' src='one.jpg'>
    <img id='id2' src='two.jpg'>
</div>

(Don't forget to change the CSS of #id2 and put display: none as initial state).

like image 87
Yves Lange Avatar answered Sep 20 '22 23:09

Yves Lange


That's elementary, use jQuery attr...

$('img#myImage').attr('src', 'image2.gif');
like image 31
mreq Avatar answered Sep 21 '22 23:09

mreq