javascriptfunction

How to change image by clicking on event?


I tried but it's not working. When I click on .imgChangeBtn element, this element’s src value will be puss on the #imgDisplay element. Note imgPath variable is not getting any value. And Anonymous function is not set on this element. I don't know why!

<img id="imgDisplay" src="default.jpg"/>
<ul>
    <li><img class="imgChangeBtn" src="wolverine.jpg"></li>
    <li><img class="imgChangeBtn" src="Iron_man.jpg"></li>
</ul>

<script>
    var DisplayBoard = document.querySelector("#imgDisplay");
    var ChangeBtn = document.querySelector(".imgChangeBtn");

    ChangeBtn.click(function () {
         var imgPath = document.querySelector('.imgChangeBtn').getAttribute('src');
         DisplayBoard.src = imgPath;

         console.log(imgPath);
   })
</script>

Solution

  • You should loop through all the elements with the class imgChangeBtn using querySelectorAll then attach the click listener using addEventListener in every iteration, check the snippet below.

    var displayBoard = document.querySelector("#imgDisplay");
    var changeBtnList = document.querySelectorAll(".imgChangeBtn");
    
    for (var i = 0; i < changeBtnList.length; i++) {
      changeBtnList[i].addEventListener('click', changeSrc);
    }
    
    
    function changeSrc() {
      var imgPath = this.getAttribute('src');
    
      displayBoard.src = imgPath;
    
      console.log(displayBoard.src);
    }
    <img id="imgDisplay" src="default.jpg" />
    
    <ul>
      <li><img class="imgChangeBtn" src="wolverine.jpg" alt="wolverine.jpg" /></li>
      <li><img class="imgChangeBtn" src="Iron_man.jpg" alt="Iron_man.jpg" /></li>
    </ul>