Javascript DOM Event prevent

Description

Javascript DOM Event prevent

View in separate window

<!DOCTYPE html> 

<html lang="en"> 
<body> 
    <a id="someLink" href="somepage.html"> 
        Click Me /*from  www .  j a va 2s  .  c  o m*/
    </a> 
    <script> 
        var evt = {
            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 link = document.getElementById("someLink"); 

        function linkClick(e) { 
            console.log("This link is going nowhere"); 

            evt.preventDefault(e); 
        } 

        evt.addListener(link, "click", linkClick); 
    </script> 
</body> 
</html> 



PreviousNext

Related