• Skip to main content
  • Skip to secondary navigation
  • Skip to footer

recoveryArea

Content Management for Everyone!

  • About me
  • Blog
  • AB Testing
  • WordPress
  • Portfolio

AB Testing

How to simulate clicks on non-supported HTML elements

4 April 2022 By iPasqualito

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…

Filed Under: AB Testing, JavaScript

Adding DOM Elements LIKE A BOSS

3 June 2021 By iPasqualito

In my AB testing Framework I have a method that creates DOM nodes, sets their properties and attributes, and adds them to the DOM for me. Since in 90% of all the tests we run, we need one or more custom elements, I decided to create a function that does all that for me. The requirements were:

  • create (one or more) DOM Element(s) by config
  • add attributes to element (class, style, innerText/ -HTML, and even events like onclick)
  • insert element in DOM relative to a target, or replace that target
  • return a reference to the element for later use

OK, let’s write a function that can do all of that – it’s possible to do it in only a few lines of code!

const buildNodesFromConfigArray = nodes => nodes.map(({tag, attributes, position, target}) => {
	// create the element
	const node = document.createElement(tag);
	// iterate through property list,
	// match innerText, innerHTML or event attributes (event attributes should be wrapped functions!),
	// else just set the attribute
	Object.entries(attributes).map(([key, value]) => (/^(inner|on)\w+$/i.test(key)) ? node[key] = attributes[key] : node.setAttribute(key, value));
	// [optional] place it in the DOM
	if (position && target) (position === "replace") ? target.replaceWith(node) : target.insertAdjacentElement(position, node);
	// return it for use in the caller function
	return node;
});

As you can see, first we create a DOM element. Then comes a pretty magical line of code if I may say so, we map over the attributes object so we can check these as key-value pair, one by one. If the regex matches on the key, we have to set either innerText or innerHTML, or an event like ‘onclick’ or ‘onmousesomething’ or whatever event you fancy. If it does not, we set an attribute with name ‘key’ and value ‘value’. Finally, if a position and target are set in our config, we add the element to the DOM relative to a target, or replace that target. Now, let’s see this awesome code in action!

// let's create a new stylesheet
const [style] = buildNodesFromConfigArray([{
	tag: 'style',
	attributes: {
		id: "ra-stylesheet",
		rel: "stylesheet",
		type: "text/css"
	},
	position: "beforeend",
	target: document.head
}]);

We declare an array and use the destructure technique to have the variable(s) immediately available to us. That way we can use it later on in our code. Like so, for instance:

style.append(document.createTextNode(`
	body {
		background-color: #00ff88;
	}
`))

Here you can see the stylesheet added to the DOM. All the properties are set like we specified.

inspect element shows the sheet where we expect it.

What if we want to add some meta tags to the head of our site? That would look like this. (You could actually skip the variable declaration if all you want is to add these to the head).

const [meta1, meta2] = buildNodesFromConfigArray([{
	tagName: "meta",
	attributes: {
		class: "ra-133-meta",
		property: "og:type",
		content: "website"
	},
	position: "beforeend",
	target: document.head
}, {
	tagName: "meta",
	attributes: {
		class: "ra-133-meta",
		property: "og:site_name",
		content: document.location.origin
	},
	position: "beforeend",
	target: document.head
}])

Here’s a final example, where we won’t be needing the elements later in our code, we just want them added in the DOM:

buildNodesFromConfigArray([{
	tagName: "div", //
	attributes: {
		class: "first",
		innerText: "My Paragraph",
		onclick: (event) => {
			// make sure the value here is an actual function!
			alert(event)
		}
	},
	position: "beforebegin", // use insertAdjacentElement position parameter, or replace
	target: document.querySelector("#someElement")
}, {
	tagName: "div",
	attributes: {
		class: "second",
	},
	position: "replace",
	target: document.querySelector("#someOtherElement")
}]);

OK, now you know how to create one or more DOM elements LIKE A BOSS. Contact me if you want to know more!

Next time, I’ll share a trick I posted on Twitter a while ago, how I exclude IE from my tests, the recoveryArea way!

Happy coding 🙂

Filed Under: AB Testing, JavaScript

My Secret to Super Fast AB Test Loading

2 June 2021 By iPasqualito

When I am testing elements that take some time to load, the last thing I want is a flash of un-styled content, or see the unchanged element jump into its changed state. Since a few years, browsers have a great API built in that I use to achieve super fast loading of my test code: Mutation Observer. (link opens new tab)

In this post I’ll explain how I use this API to my advantage.

Make sure your script is loaded as soon as possible. It’s OK if you load it asynchronously, but you want it to be available as the first piece of JS the page is loading.

Here’s the function I use to observe when an element gets added to the DOM. I basically wrap a querySelector in a MutationObserver. The latter will fire upon every DOM mutation. The querySelector will then test for the existence of my element. If that returns true, I disconnect the observer if I don’t need it anymore. Finally, I run the callback function that was passed as the second parameter.

const observeDOM = (config, callback) => {
    // use a regular function so `this` refers to the Mutation Observer
    new MutationObserver(function() {
        const element = document.querySelector(config.selector);
        if (element) {
            // disconnect if you don't need it again
            if(config.disconnect) this.disconnect();
            // test and run the callback function
            if(typeof callback === "function") callback(element);
        }
    }).observe(config.parent || document, {
        subtree: config.recursive,
        childList: true
    });
}

I use a ‘normal’ function keyword on the Mutation Observer function because if I don’t, I won’t be able to disconnect it if that is what I want. This will then refer to the Window object and not the MutationObserver instance.

const config = {
    selector: 'li.timeline-item', // what element are we looking for?
    parent: document.querySelector("ul.timeline"), // narrow down search scope if possible...
    recursive: true, // look at descendant elements too
    disconnect: false // set to true when one hit is enough
}

In the config file above you can see that I am observing an unordered list for additions of list items. Since disconnect is set to false, the observer will fire on every mutation and do the element test again. Note: You can prevent triggering on the same element over and over again by adding a class (.found) to the element as soon as it’s found, and change your selector accordingly: a li.timeline-item:not(.found) selector does that trick just fine.

// run this function when the element is found
const callback = console.log;

Here is a simple example of a callback function you can run when you have a hit. In your case you probably want to kick off your AB test code. See what I did there?

// kickoff mutation observer
observeDOM(config, callback);

Last but not least, you want to start observing by calling your function with config and callback parameters.

In the next post, I’ll show you how to create DOM elements – recoveryArea style!

Happy coding!

Filed Under: AB Testing, JavaScript

Notify Enter Viewport the proper way: Intersection Observer.

4 February 2020 By iPasqualito

In previous articles I have written about how to track elements when they enter or leave the browsers viewport. The reason why you might want to track this is when you are doing a test on an element that is outside the viewport on page initialisation, you don’t want to count this as a visitor immediately but only when the element is scrolled into view.

If the (changed) element is seen by the visitor, you fire an event, not before. In the past I accomplished this by using something called notify enter viewport. This worked just fine but it came with a lot of caveats.

For instance, notify enter viewport only accepts elements that are already loaded in the DOM. Second, a lot of calculations have to be done inside the function before we know an elements position. It’s complicated.

Modern browsers come with an API that can help us accomplish basically the same in a much simpler way, the Intersection Observer.

Here’s a code example of how I use it in my own AB testing framework.


const observeIntersections = function (config) {
    // loop through all entries in config array
    config.forEach(function (options) {

        document.querySelectorAll(options.element).forEach(function (element) {

            const observer = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {

                    if (entry.isIntersecting) {

                        sendDimension({
                            event: 'trackEventNI',
                            eventCategory: abtest.testid + ": " + abtest.testName,
                            eventAction: 'Viewport hit for element [' + element + ']',
                            eventLabel: abtest.variation,
                            eventNonInteraction: true
                        });

                    }
                });
            }, {
                root: null, // use document viewport as container
                rootMargin: "0px",
                threshold: 1 // fire callback as each of these thresholds is reached
            });

            observer.observe(element);

        });

    })
};

observeIntersections([{
        element: 'h4', // the element or elements we want to observe
        tag: 'H4 Element',
        threshold: 1,
        root: null,
        rootMargin: "0px"
    }, {
        element: 'h2#Intersection_observer_concepts_and_usage',
        tag: 'H2 title element',
        threshold: 1,
        root: null,
        rootMargin: "0px"
    }, {
        element: 'iframe.live-sample-frame.sample-code-frame',
        tag: 'IFRAME ELEMENT',
        threshold: [0, 0.5, 1],
        root: null,
        rootMargin: "0px"
    }
]);

Filed Under: AB Testing, JavaScript

Notify Enter Viewport

21 June 2018 By iPasqualito

Sometimes we are testing a page element or component that, when the page has loaded, lies outside of the viewport. This has the simple consequence that you should not count this page load as a visitor to your test. Only when the element you are testing scrolls into view, the visitor can be added to your test. To accomplish this, we needed some code that keeps track of the elements position on the page with regard to the page’s dimensions.

This one still relies on jQuery, I’ll upload a JS only version soon.

var notifyEnterViewport = function(o) {
        var raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame,
            l = $(window).height(),
            r = $(window),
            t = r.scrollTop(),
            enter = function(e) {
                e.addClass("MM_inside_viewport"), e.hasClass("MM_outside_viewport") && e.removeClass("MM_outside_viewport")

            },
            exit = function(e) {
                e.addClass("MM_outside_viewport"), e.hasClass("MM_inside_viewport") && e.removeClass("MM_inside_viewport")
            },
            loop = function() {
                var e = r.scrollTop();
                t !== e && (t = e, o.length && $.each(o, function(e) {
                    var o = $(this),
                        raf = o.height(),
                        t = o.offset().top,
                        loop = t - r.scrollTop(),
                        n = t - r.scrollTop() + raf;
                    0 <= loop && n <= l && !o.hasClass("MM_inside_viewport") && (console.log("test: element " + (e + 1) + " scrolled into view"), enter(o)), (n < 0 || l < loop) && !o.hasClass("MM_outside_viewport") && (console.log("test: element " + (e + 1) + " scrolled out of view"), exit(o))
                })), raf(loop)
            };
        raf && loop();
    }
    elementsToCheck = $("div#checkThisElement");
notifyEnterViewport(elementsToCheck);
  • UPDATE!


var notifyEnterViewport = function(el) {
    var w = window,
        raf = w.requestAnimationFrame,
        vpHeight = w.innerHeight,
        lastPgYO = w.pageYOffset,
        scroll = function() {
            var height = el.offsetHeight,
                elOffset = offSet(el),
                top = elOffset.top,
                pTop = top - w.pageYOffset,
                pBottom = pTop + height;
            if (pTop >= 0 && pBottom <= vpHeight && !el.classList.contains('mm_enter')) {
                enter(el);
            }
            if ((pBottom < 0 || pTop > vpHeight) && !el.classList.contains('mm_exit')) {
                exit(el);
            }
        },
        offSet = function(el) {
            var rect = el.getBoundingClientRect(),
                pgxo = w.pageXOffset,
                pgyo = w.pageYOffset;
            return {
                top: rect.top + pgyo,
                left: rect.left + pgxo
            };
        },
        enter = function(el) {
            //console.log("enter: ", el);
            el.classList.add('mm_enter');
            el.classList.remove('mm_exit');
        },
        exit = function(el) {
            //console.log("exit: ", el);
            el.classList.add('mm_exit');
            el.classList.remove('mm_enter');
        },
        loop = function() {
            var PgYO = w.pageYOffset;
            if (lastPgYO === PgYO) {
                raf(loop);
                return;
            } else {
                lastPgYO = PgYO;
                scroll();
                raf(loop);
            }
        };
    if (raf) loop();
};

// call:
notifyEnterViewport(document.querySelector('ul#sub_nav > li.active:not(.first)'));

Filed Under: AB Testing, JavaScript

AB Test jQuery Performance Cheat Sheet

14 October 2016 By iPasqualito

cheating

If you write AB tests with jQuery you have to make sure you write your code as optimised as possible. Every millisecond you shave off results in less chance of unwanted repaint or reflow flickers.

Update: Tip number 1: Do NOT use jQuery! Why wait for a library to load, when vanilla JS nowadays does everything jQuery does – but faster.

Use Faster Selectors.

Know which selectors perform the fastest to optimise your code!

// ID selector - very fast (document.getElementById)
$("#id");
// TAG selector - fast (document.getElementsByTagName)
$("p");, $("input");, $("form");
// CLASS selector - performs well in modern browsers (document.getElementsByClassName)
$(".class");
// ATTRIBUTE SELECTOR - slow - needs document.querySelectorAll to perform OK-ish
$("[attribute=value]");
// PSEUDO selector - slowest - needs document.querySelectorAll to perform OK-ish
$(":hidden");

// also, instead of this:
$("#id p");
// do this:
$("#id").find("p"); // --> limit the scope that has to be searched: more than twice as fast!

Use Caching.

Basically every time you use

$('someselector')

you iterate through the dom. If you need an element more than twice, you should store the element reference!

// instead of this:
$('a.contactus').css('padding', '10px');
$('a.contactus').css('margin', '4px');
$('a.contactus').css('display', 'block');
// do this:
var myvar = $('a.contactus');
myvar.css({
padding: '10px',
margin: '4px',
display: 'block'
}); // element stored, CSS passed as object

Use Chaining.

Chained methods will be slightly faster than multiple methods made on a cached selector, and both ways will be much faster than multiple methods made on non-cached selectors.

// instead of this
$("#object").addClass("active");
$("#object").css("color","#f0f");
$("#object").height(300);
// do this
var myvar = $('a.contactus');
myvar.addClass("active").css("color", "#f0f").height(300);

Use Event Delegation.

Event listeners cost memory.

// instead of this: (an event listener for EVERY table cell)
$('table').find('td').on('click',function() {
$(this).toggleClass('active');
});
// do this: (an event listener for only the table that gets fired by its 'td' children)
$('table').on('click','td',function() {
$(this).toggleClass('active');
});

Use Smarter DOM Manipulation.

Every time the DOM is manipulated, the browser has to repaint and reflow content which can be extremely costly.

// instead of this:
const arr = [reallyLongArrayOfImageURLs];
$.each(arr, function(count, item) {
let newImg = '<li><img src="'+item+'"></li>';;
$('#imgList').append(newImg); // aargh a selector in a loop! and we're adding an element here, too!
});
// do this
var arr = [reallyLongArrayOfImageURLs],
tmp = '';
$.each(arr, function(count, item) {
tmp += '<li><img src="'+item+'"></li>'; // no selector and the HTML to add is stored in a variable...
});
$('#imgList').append(tmp); // ..that will be added once when the loop has finished

Filed Under: AB Testing, JavaScript, Performance

Footer

Office

recoveryArea
Nijverheidstraat 11-1
7511 JM Enschede

KvK: 65594940

Goals

Let's make a more elegant, easy to use internet, accessible for everyone. Let's move forward to an empathic, secular, sustainable future, enabled through science and technology.

Read my full profile

Get in touch

  • GitHub
  • LinkedIn
  • Twitter

Copyright © 2025 · From recoveryArea with