• Seo Expert
  • Khaali Paper

Changing the Image

JavaScript changes the value of the src (source) attribute of an image on based on click changeImg() function.


more or less

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
  • JavaScript
  • Example
<img src="img/more.jpg" id="myImg" width="40" height="40">
<input type="button" onclick="changeImg()" value="Change" />
<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>
<!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.

<!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
more or less
<img src="COVER_IMAGE" onmouseover="this.src='OTHER_IMAGE'" onmouseout="this.src='COVER_IMAGE'">