Capture DOM click event in JavaScript and trigger at later time

2.3k Views Asked by At

Been researching this concept for a while now, and still not certain on best approach.

I'd like to capture a click event and trigger any (default or manually attached) events that follow it at a later time. More specifically, I want to record a tracking event when an element in the .container is clicked. After it's been recorded, I want to resume the behaviors of the clicked element. Is this functionality attainable in this manner?

<div class="container">
    <span>My Text</span>
    <a href="/myurl">My Link</a>
    <button type="submit">My Button</button>
</div>

I'm adding a click event to the element (whether it has others already or not), and capturing and preventing it's default behavior:

elementInsideContainer.addEventListener('click',e => {
    e.preventDefault();
    // submit some click tracking data via ajax
    // carry on with other events on element
});

I know I have access to srcElement.href and could window.location the user there when capturing a click event on an <a> tag, but could that really be the best way to do this? What if the element is a type=submit button or just a <span>CLICK ME!</span> that I want to track (as shown above)? Been reading about dispatchEvent(event) but not sure if it's what I'm looking for.

1

There are 1 best solutions below

2
karthick On

I think you shouldn't block the event flow just because you want to record an event. If this is part of analytics it should always be outside your main implementation. I suggest you to register a generic event handler in capturing phase and track the event calls through that. The events should continue irrespective of whether the events are saved in your database or not. This script should reside in your tag manager. So you don't have to copy the script again and again.

Sample implementation:

var body = document.querySelector('body');

body.addEventListener('click',e=> { 
   console.log(e.target, e.type)
   var data = {"name": e.target.nodeName, "id": e.target.id, "class": e.target.classList, "eventType": e.type };
    fetch("https://requestb.in/14ihhbd1", {
        body: JSON.stringify(data),
        method: 'POST',
    mode: 'cors', 
    });
}, true);

Note: The bin url will timeout after sometime. But you can create your own and play with it and see how it captures all the actions.