Javascript DOM Event Add and Remove Multiple Event Handlers

Description

Javascript DOM Event Add and Remove Multiple Event Handlers

View in separate window



<!DOCTYPE html> 

<html lang="en"> 
<body> 
    <img id="img0" src="image1.png" /> 
    <div id="status"></div> 
    <script> 
        var evt = {/*from   ww w .  java  2s . c  om*/
            addListener: function(obj, type, fn) {
                if (typeof obj.addEventListener != "undefined") {
                    obj.addEventListener(type, fn);
                } else {
                    obj.attachEvent("on" + type, fn);
                }
            },
            removeListener: function(obj, type, fn) {
                if (typeof obj.removeEventListener != "undefined") {
                    obj.removeEventListener(type, fn);
                } else {
                    obj.detachEvent("on" + type, fn);
                }
            },
            getTarget: function(e) {
                if (e.target) {
                    return e.target;
                }
        
                return e.srcElement;
            },
            preventDefault : function(e) {
                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    e.returnValue = false;
                }
            }
        };    
        let myImages = [ 
            "image1.png", 
            "image3.png", 
            "image4.png", 
            "image2.png" 
        ]; 

        function changeImg(e) { 
            let el = evt.getTarget(e); 
            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 = evt.getTarget(e); 
            let status = document.getElementById("status"); 

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

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

        let imgObj = document.getElementById("img0"); 
          evt.addListener(imgObj, "click", changeImg); 
          evt.addListener(imgObj, "click", updateStatus); 
      </script> 
  </body> 
  </html> 



PreviousNext

Related