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 <svg> 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 <svg> 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ā¦