Firing a tracking pixel on button click without GTM
As a solutions engineer in Adtech, sometimes we have to create ways to bend the will of the browser for our clients. One of our clients wanted to fire a tracking pixel on a button click. With Google Tag Manager this is very easy, you just use a custom trigger using a CSS selector. The client wasn't using Google Tag Manager (GTM) so I put this together.
<button id="unique_id">click me</button>
<script type="text/javascript">
(() => {
const b = document.getElementById('unique_id');
b.onclick = () => {
const i = document.createElement('img');
i.src = '< your pixel src goes here >';
i.setAttribute('width', 0);
i.setAttribute('height', 0);
b.parentElement.appendChild(i);
};
})();
</script>
Breakdown
The first bit is pretty simple, this is out button.
<button id="unique_id">click me</button>
The next part is where the pixel gets appended to the body on button click where it's then fired.
<script type="text/javascript">
(() => {
const b = document.getElementById('unique_id');
b.onclick = () => {
const i = document.createElement('img');
i.src = '< your pixel src goes here >';
i.setAttribute('width', 0);
i.setAttribute('height', 0);
b.parentElement.appendChild(i);
};
})();
</script>
I have set up anonymous function, which gets the button by its ID and stores it into the variable b
.
Then a click handler is added to b
which allows us to do what we need to when the button is clicked. Once the button is clicked we create our img
HTML element, we then set its height and width via setAttribute
we set this to 0
. Then we append it to the parent element which is the HTML body.
This is when the pixel is fired.
All in all pretty simple, but a cool little way of achieving what the client wants when they were using GTM.