P K P K - 1 month ago 17
Javascript Question

Can i attach capture and bubble phase event handler on the same element?

Can i attach capture and bubble phase event handler(could be different or same function) on the same element?

I tried it and it's working fine.

Is it permitted as per W3C?
I don't see any limitation or restriction mentioned in the DOM3 Event specification.

Could someone please clarify it?

var divList = document.getElementsByTagName('div');
var eventHandler = function(event){
console.log(event.currentTarget);
}
for(var index=0; index < divList.length; index++){
divList[index].addEventListener('click',eventHandler,true);
divList[index].addEventListener('click',eventHandler,false);
}

Answer

Yes, binding events to both phases is allowed. Here are a few instances where it is very useful:

  • Programmatic filling of form fields
  • Programmatic queueing of form submit events
  • Programmatic syncing of multiple select elements

Some events, such as focus, don't bubble but can be captured. The inline handler on the target element triggers before capture handlers for the target element.

Many newly specified events in the web platform (such as the media events) do not bubble, which is a problem for frameworks like Ember that rely on event delegation. However, the capture API, which was added in IE9, is invoked properly for all events, and does not require a normalization layer. Not only would supporting the capture API allow us to drop the jQuery dependency, but it would allow us to properly handle these non-bubbling events. This would allow you to use events like playing in your components without having to manually set up event listeners.

References

Comments