Javascript DOM Event handler add and remove

Description

Javascript DOM Event handler add and remove

View in separate window

  <!DOCTYPE html> 

  <html lang="en"> 
  <body> 
      <img id="img0" src="image1.png" /> 
      <div id="status"></div> 

      <script> 
          let myImages = [ //from   ww w  .ja  v  a2s  .  co m
              "image1.png", 
              "image3.png", 
              "image4.png", 
              "image2.png" 
          ]; 

          function changeImg(e) { 
              let el = e.target; 
              let newImgNumber = Math.round(Math.random() * 3); 

              while (el.src.indexOf(myImages[newImgNumber])  != -1) { 
                  newImgNumber = Math.round(Math.random() * 3); 
              } 

              el.src = myImages[newImgNumber]; 
          } 

          function updateStatus(e) { 
              let el = e.target; 
              let status = document.getElementById("status"); 

              status.innerHTML = "The image changed to " + el.src; 

            if (el.src.indexOf("mexico") > -1) { 
                el.removeEventListener("click", changeImg); 
                el.removeEventListener("click", updateStatus); 
            } 
        } 

        let imgObj = document.getElementById("img0"); 

        imgObj.addEventListener("click", changeImg); 
        imgObj.addEventListener("click", updateStatus); 
    </script> 
</body> 
</html> 



PreviousNext

Related