Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the source of an image dynamically in HTML?

Tags:

html

Please help me with this question I am trying to change the source of an image dynamically.

like image 534
Josh Avatar asked Dec 21 '09 19:12

Josh


People also ask

How do I change a dynamic element in HTML?

The easiest way to modify the content of an HTML element is by using the innerHTML property . The innerHTML property gets or sets the HTML or XML markup contained within the element.

How to change the image source with JavaScript?

JavaScript provides a src attribute to change the image source by specifying the path of the file. For instance, the getElementId() method is utilized to extract the HTML element through id, and then the src property will change the source image. After extraction, the new source image file is assigned.

How to set dynamic image path in JavaScript?

Use id into img tag and getElementById method then assign imager source to set image src in JavaScript. document. getElementById('image'). src = 'http://yourImagePathHere';


1 Answers

Client-side (Dynamic) Image-Swapping...

You'll need to use javascript for this:

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

<script type="text/javascript">
  document.getElementById("myImage").src = "image2.jpg";
</script>

Introducing jQuery...

If this is the type of response you are looking for, then I would also like to extend an invitation to you to start checking out and javascript framework like jQuery, which makes this type of stuff much easier to do/manage. In jQuery, you can accomplish the same thing with the following code:

$("#myImage").attr("src", "image2.jpg");
like image 176
Sampson Avatar answered Oct 21 '22 21:10

Sampson