How to catch click events on a link in order to fire a pixel

AI-generated summary

The discussion revolves around catching click events on a link to fire a pixel to Google AdWords. alonle initially asked for help and provided a link to a similar topic on meta discourse, which involved using a script to catch click events within a topic posting form.

joebuhlig suggested using jQuery via a customization, providing a script that logs a string every time a topic title is clicked. This script can be altered to catch click events on every link on the site.

alonle confirmed that the script worked and ended up using api.onPageChange along with setTimeout to set the click binding after page rendering. However, eviltrout warned that using setTimeout is unreliable for determining when elements are rendered, as it may fire before rendering is complete.

Hi @team, Is there any way to catch click event on a link and fire a pixel to google adwords.
I want to know if user click on an amazon link on my site.

I saw this topic
https://meta.discourse.org/t/how-to-catch-click-events-within-topic-posting-form-with-jquery/36184

Anything similar to this code can be done with a link? (html a href)

Thanks

You should be able to catch click events with jquery via a customization. Put this in the </head> section:

<script type="text/discourse-plugin" version="0.2">
    Discourse.PageTracker.current().on('change', function () {
        $(".topic-list-item .title").on("click", function(){
            console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        })
    })
</script>

This will log the string of x`s every time you click on the title of a topic in a list of topics. You could alter this to do whatever you please for every link on the site.

Thanks, it worked, I end up using the api.onPageChange and also add setTimeout since the page changed and not all page was render to set the click binding.

I should warn you that setTimeout is unreliable for knowing when things are rendered. It might work in your testing but there could be times when the timeout fires before things have been rendered.