I have an image with a default src
like this:
<img src="../template/edit.png" name="edit-save" alt="Edit" />
I want to change the src
of the image to “…/template/save.png” when it’s clicked. Here’s my HTML with the onclick
:
<a href="#" onclick="edit()">
<img src="../template/edit.png" id="edit-save" alt="Edit" />
</a>
And my JavaScript function looks like this:
function edit() {
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
}
I tried adding the following to change the image:
var edit_save = document.getElementById("edit-save");
edit_save.onclick = function() {
this.src = "../template/save.png";
};
However, I need to click the image twice for it to work. How can I fix this to make it work smoothly on the first click using JavaScript change image src?
Change the src inside your edit()
function directly : This is the simplest and cleanest fix! You’re already calling edit()
on click, so why not just change the src in that same function?
This avoids double clicks entirely and gives you precise control. It’s one of the smoothest ways to use JavaScript change image src.
function edit() {
var inputs = document.myform;
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
document.getElementById("edit-save").src = "../template/save.png";
}
Instead of using onclick in your HTML, hook into the image using JavaScript once the DOM loads:
This method makes sure the handler is attached after the element exists and avoids timing issues. A clean and modular way to handle JavaScript change image src dynamically.
window.onload = function () {
document.getElementById("edit-save").addEventListener("click", function () {
this.src = "../template/save.png";
});
};
If you want to toggle back and forth (like Edit ↔ Save), you can introduce a little logic:
let isEditing = false;
function edit() {
var inputs = document.myform;
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = !isEditing;
}
const img = document.getElementById("edit-save");
img.src = isEditing ? "../template/edit.png" : "../template/save.png";
isEditing = !isEditing;
}
This way, each time the image is clicked, it toggles between two states. It’s a great enhancement if you’re planning to flip between two icons using JavaScript change image src in a more interactive UI.