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.
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.
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.
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.
JavaScript code to get the HTML img tag src attribute valuevar img_src = document. getElementById("my-img"). src; console. log(img_src);
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).
That's elementary, use jQuery attr...
$('img#myImage').attr('src', 'image2.gif');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With