-4

Is there a way to overwrite an image already existing in my site using javascript... if yes, what method, and any links for tutorials?

3 Answers3

1

This is a code example in Js :

<script language="javascript">
function ChangeImageSrc(oldSrc, newSrc) {
    var imgElements = document.getElementsByTagName('img');
    for (i = 0; i < imgElements.length; i++){
        if (imgElements[i].src == oldSrc){
            imgElements[i].src = newSrc;
            break;
        }
    }
}
</script>
1

You only need to change the src attribute of your image, you can do something like this:

<script>
function myFunction() {
    var x = document.getElementById("myImg").src = 'image2.jpg';
}
</script>
<img src="image1.jpg" id="myImg">
<button onclick="myFunction()">Change Image </button>
Luis
  • 56
  • 4
0

You can't do this with javascript alone - you will need to have something on your server to actually handle the saving of the image. If you want to overwrite an image, you would simply need to provide the same filename when saving and apply the appropriate permissions.

There are lots of resources available for file/image uploads, eg:

https://joelvardy.com/writing/javascript-image-upload
https://css-tricks.com/ajax-image-uploading/

The right solution for you depends on what you have available on your server.

duncanhall
  • 11,035
  • 5
  • 54
  • 86