I’m trying to write my own function to block events.
Here is what I have:
function disableEvent (element, event, useCapture) {
function preventer (event) {
event = event || window.event;
event.preventDefault() ? event.preventDefault() : (event.returnValue = false);
event.stopPropagation() ? event.stopPropagation() : (event.cancelBubble = true);
}
if (typeof useCapture == 'undefined') useCapture = false;
if (element.addEventListener)
element.addEventListener(event.toLowerCase().substr(2), preventer, useCapture)
else if (element.attachEvent) {
var result = element.attachEvent(event,preventer);
return result;
}
else {
alert("Try to change or update your browser")
}
}
But it does not work on IE browser. It shows me an error on 4th line. Appreciate your help with this task.
When trying to test if function exists, you write:
Let us analyse this.
event.stopPropagation()is a call toevent.stopPropagationwithout parameters, it doesn’t return anything, that meansundefined. So you’ll face one problem:if
stopPropagationdoesn’t exist, you are still calling it. It produces an error, that’s what happens in your case.To avoid this problem, you have to check weither the function exists or not:
It should work properly. Same thing with
preventDefault.