JavaScript change image onclick event
JavaScript changes the value of the src (source) attribute of an image on based on click changeImg() function.
Based on click we can replace the image with another image using JavaScript. Below are the image tag with src and ID. Based on id and changeImg() function we can change the image src.
HTML
<img src="img/more.jpg" id="myImg" width="40" height="40">
<input type="button" onclick="changeImg()" value="Change" />
JavaScript
<script type="text/javascript">
function changeImg() {
var image = document.getElementById('myImg');
if (image.src.match("img/more.jpg")) {
image.src = "img/less.jpg";
}
else {
image.src = "img/more.jpg";
}
}
</script>
Example
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<img src="img/more.jpg" id="myImg" width="40" height="40">
<input type="button" onclick="changeImg()" value="Change" />
<script>
function changeImg() {
var image = document.getElementById('myImg');
if (image.src.match("img/more.jpg")) {
image.src = "img/less.jpg";
}
else {
image.src = "img/more.jpg";
}
}
</script>
</body>
</html>
Change an image on hover
Use HTML + CSS for one picture change to another when you hover over it.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Change Image on Hover in CSS</title>
<style type="text/css">
.img-replace {
width: 40px;
height: 40px;
background: url("../img/more.jpg") no-repeat;
}
.img-replace:hover {
background: url("../img/less.jpg") no-repeat;
}
</style>
</head>
<body>
<div class="img-replace"></div>
</body>
</html>
Use inline JavaScript for change image in hover
<img src="COVER_IMAGE" onmouseover="this.src='OTHER_IMAGE'" onmouseout="this.src='COVER_IMAGE'">
You can customize this code further as per your requirement.