STAGING not indexed production at recoveryarea.nl

javascript · · 2 min read

How to simulate clicks on non-supported HTML elements

Why HTMLElement.click() silently fails on SVG, and the modern MouseEvent-dispatch one-liner that actually triggers the click on any element.

An SVG element with a click ripple paired with the dispatchEvent line that actually triggers the click

Working on an AB test, I had to write some code that involved using a clone for a clickable element. The original HTML element, an element, had to be hidden and replaced by a button. What this button should do is simple: hide a pop up on click.

My first thought was, I add a click event listener to that button and just pass that click to the original element like so:

// (this code is what my ab test framework expects to create an HTML element ;) )
{
   tagName: "a",
   attributes: {
	  class: "a-button a-button--size-small a-button--mode-primary a-button--color-red ra-031-pin-weiter-button",
	  innerHTML: `<div class="a-button__text">Weiter mit gewählten Markt</div>`,
	  onclick: () => closeButton.click() // simple, right?
   },
   position: "beforeend",
   target: messageContainer
}

Simple! Thank you all those years of experience, this should do the trick, right?

What I did not yet realize however was that elements do not support the HTMLElement.click() method so running into this error kind of stumped me…:

So then I started looking for a solution. The first thing I found was this, and it looked promising, but somehow did not cut the cake for me:

// click() is a function that's only defined on HTML elements.
// Fortunately it's a convenience function that we 
// can implement it ourselves pretty easily like so:

const target = document.querySelector("svg");

target.dispatchEvent(new Event('click'));

Also, since the handler for the original element’s click event was out of reach for me, I could not approach it directly so I just had to find a way to make this simulated click work.

Then I found this piece of code, but when I started using it I discovered that parts of it were deprecated but, great news, now I was getting somewhere! The click actually worked!

const ev = document.createEvent("SVGEvents");
ev.initEvent("click",true,true); // deprecated.. :(

target.dispatchEvent(ev);

But.. using deprecated code is something I rather avoid. Looking for an even better solution should not be that hard anymore since I’m looking in the right direction. Then I found this, the final solution to my problem and come to think of it, quite predictable 😉

const dispatchClick = target => {
   const ev = new MouseEvent('click', {
	  view: window,
	  bubbles: true,
	  cancelable: true
   });
   target.dispatchEvent(ev);
};

Guess when you’re confused by a totally unexpected error, finding the correct solution sometimes takes you on a slight detour…