Growing with the Web

Redirecting DOM events

Published
Tags:

Sometimes it’s necessary to redirect a particular event on an element to another element, not just bubble it up through the element’s ancestors. Since an Event cannot be reused once it is thrown, that means it needs to be recreated before being dispatched.

The modern way to create events is by passing in a dictionary to the event constructor, for example:

var newEvent = new MouseEvent('click', {
  /* ...properties... */
});

It’s somewhat cumbersome though to include all the properties. And since the original event already has these fields, it can be used as the dictionary!

function clickHandler(event) {
  var newEvent = new MouseEvent(event.type, event);
}

Now it’s just a matter of dispatching the new event to whatever the event is being redirected to.

function redirectMouseEvent(event) {
  element.dispatchEvent(new MouseEvent(event.type, event));
}

This can even be taken one step further to make a function for completely generic event redirection.

function redirectEvent(eventType, fromElement, toElement) {
  fromElement.addEventListener(eventType, function (event) {
    toElement.dispatchEvent(new event.constructor(event.type, event));
    event.preventDefault();
    event.stopPropagation();
  });
}

var foo = document.querySelector('#foo');
var bar = document.querySelector('#bar');
redirectEvent('click', foo, bar);

Like this article?
Subscribe for more!