-4

Beginner here. I have a series of HTML IMG elements that look like this:

<img src="1.png" onclick="changeImg(this)">
<img src="2.png" onclick="changeImg(this)">
<img src="3.png" onclick="changeImg(this)">

What I would like the "changeImg" JS function to do is, on click, change the image source from "1.png" to "1.gif". Essentially, just changing the last 3 letters of the img source.

The purpose of this is to allow users to click on an element in order to play an animated GIF. As such, "1.png" is simply a static PNG version of the animated "1.gif". Can this be done?

Chris
  • 1
  • 2
  • I've been googling and stuck for a while now, because all the solutions I can find merely substitute a new IMG src, not alter it. I want to be able to do more than that. This is not a very constructive or helpful comment. – Chris Oct 22 '20 at 06:50

2 Answers2

1

Use img.src:

function changeImg(img) {
  img.src = img.src.replace('png', 'gif');
}
<img src="1.png" onclick="changeImg(this)">
benhatsor
  • 1,863
  • 6
  • 20
0
// this is jquery code
// In this way, no matter what your src suffix is, it can be changed to gif
function changeImg(obj){
    var nowSrc = $(obj).attr("src");
    var srcName = nowSrc.split(".");
    $(obj).attr("src",srcName[0]+".gif");
}

But why is it so troublesome? Is it not good to directly change src to 1.gif?

Because the sports picture does not have to have the same name as the static picture, what if the sports picture is 1.jpg and the sports picture is 2.gif?

This should be better. When generating the page, directly generate the img tag into the following form:

<img src = "Static image URL from server" onclick = "changeImg(this, "Dynamic image URL from server")">
<img src = "Static image URL from server" onclick = "changeImg(this, "Dynamic image URL from server")">
<img src = "Static image URL from server" onclick = "changeImg(this, "Dynamic image URL from server")">
// this is jquery code
function changeImg(obj, url){
    $(obj).attr("src", url);
}

In this way, the names of the two pictures do not have to be the same, which is more flexible