I want to click on a image and that it changes into another but it wont work, i used the code from w3schools.com but it won't work either
this is the code:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" onclick="changeImage()" src="img/checkoff.png">
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon")) {
image.src = "checkoff.png";
} else {
image.src = "checkon.png";
}
}
</script>
</body>
</html>
there is a issue in your code
here you use only name of image file with extension you need to also give a relative file path of image: like this
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon")) {
image.src = "img/checkoff.png";
} else {
image.src = "img/checkon.png";
}
}
Here you can check this example.
It is working smoothly.
Hope this will helps you
function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("generic-image-placeholder")) { image.src = "https://cdn.noths-static.com/system/product_images/images/001/037/649/original_set-of-eight-white-heart-name-place-holders.jpg"; } else { image.src = "https://www.webpagefx.com/blog/images/cdn.designinstruct.com/files/582-how-to-image-placeholders/generic-image-placeholder.png"; } }
<!DOCTYPE html> <html> <body> <img id="myImage" onclick="changeImage()" src="https://cdn.noths-static.com/system/product_images/images/001/037/649/original_set-of-eight-white-heart-name-place-holders.jpg"> </body> </html>
Try Below code is working
<img id="myImage" onclick="changeImage()" src="http://fakeimg.pl/300/">
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("http://fakeimg.pl/250x100/")) {
image.src = "http://fakeimg.pl/300/";
} else {
image.src = "http://fakeimg.pl/250x100/";
}
}
</script>
Click Here to see jsFiddle Demo
Your code please change path when click on image
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon.png")) {
image.src = "img/checkoff.png";
} else {
image.src = "img/checkon.png";
}
}
</script>
Image path is not correct in your code. Please update as below :
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("checkon")) {
image.src = "img/checkoff.png";
} else {
image.src = "img/checkon.png";
}
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.