So I'm just messing around with HTML and Javascript and I was wondering how to make it so where a user clicks on an image and then that image changes after the click. At first I thought it would be a simple function call on a onclick like so:
HTML:
<input type="image" src="Images/img.png" id="img" onclick="imgChange()">
Javascript:
function imgChange()
{
var img = document.getElementById("img");
img.src="Images/img2.png";
}
but when executing it it doesn't seem to work. Any suggestions?
It works perfectly fine
function imgChange() {
var img = document.getElementById("img");
img.src="https://live.staticflickr.com/7166/6621290239_250dce025d_b.jpg";
}
<input type="image" src="https://live.staticflickr.com/7440/8838399307_9e9e9668f6_b.jpg" id="img" onclick="imgChange()">
You can also try moving the images to the same directory as the HTML file to make it simpler.
Seems to work perfectly in the example below. I would suggest checking that the references to the image sources you are using are valid, as that's the only thing I changed.
function imgChange() {
var img = document.getElementById("img");
img.src = "https://www.tompetty.com/sites/g/files/g2000007521/f/styles/photo-carousel/public/Sample-image10-highres.jpg?itok=TDZEPjP8";
}
<input type="image" src="https://www.tompetty.com/sites/g/files/g2000007521/f/styles/photo-carousel/public/sample001.jpg?itok=0Riiujkr" id="img" onclick="imgChange()">
should work as is, but you could try passing the element into the function.
function imgChange(img){
img.src = "https://w.wallhaven.cc/full/pk/wallhaven-pkgkkp.png"
}
<img src="https://w.wallhaven.cc/full/rd/wallhaven-rdwjj7.jpg" onclick="imgChange(this)">