Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulate W3C event capturing model in IE

Is it possible to emulate event capturing in Internet Explorer?

An example:

<a>one</a>
<a>two</a>
<a>three3</a>

<script>
var links = document.getElementsByTagName("A");
for (var i=0; i < links.length; i++) {
  links[i].onclick = function(){
    alert("clicked");
  };
}
</script>

I want to prevent all these click events from firing. I can do that with a single event observer:

document.addEventListener("click", function(e) {
    e.stopPropagation();
    e.preventDefault();
}, true);

How can I do the same in IE? IE < 9 does not support addEventListener. It does support attachEvent, but it doesn't have useCapture option.

I've found setCapture method, but it doesn't look related to the W3 capturing model.

like image 496
NVI Avatar asked Sep 03 '10 17:09

NVI


People also ask

What is the difference between event capturing and event bubbling?

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.

What is the use of event capturing in javascript?

Event capturing is one of two ways to do event propagation in the HTML DOM. In event capturing, an event propagates from the outermost element to the target element. It is the opposite of event bubbling, where events propagate outwards from the target to the outer elements. Capturing happens before bubbling.


1 Answers

Generally you can't because of the event order. In IE the events will start bubbling from the target element without the capturing phase so you can't catch them beforehand.

There's only one thing you can do, and it's only possible if you manage all the event handlers.

  1. Write a wrapper for addEvent with capture parameter
  2. If capturing is required do the following

    1. Register a simple bubbling event, with a function that
    2. Goes all the way up the parent chain, saving all the elements to an Array
    3. Travels backward this Array invoking the original event handler on each of the elements
like image 143
25 revs, 4 users 83% Avatar answered Oct 17 '22 10:10

25 revs, 4 users 83%