Mixpanel track_links does not work with dynamically added elements

I am having problems using mixpanel.track_links with links added dynamically (after the page loads).

For the general example given on this page:

<div id="link-div"></div> <input type="button" id="add-link" /> <script type="text/javascript"> mixpanel.track_links(".mixpanel-event", "event name", function(ele) { return { "type": $(ele).attr("type")}}); </script> 

When a user action is performed, links are added to the page using jquery. For instance:

 $('#add-link).click(function() { $('#link-div').html('<a class="mixpanel-event" type="event-type" href="#>Link to track</a>'); }) 

The problem is that track_links does not start when you click on a link you just created. I hope someone can share their experience in enabling the track_link function for dynamically added links.

+6
source share
1 answer

I was curious, so I checked their code and went ahead and did as they suggested. I tested it and it worked fine. However, this requires jQuery.

Usage example: mixpanel.delegate_links(document.body, 'a', 'clicked link');

 // with jQuery and mixpanel mixpanel.delegate_links = function (parent, selector, event_name, properties) { properties = properties || {}; parent = parent || document.body; parent = $(parent); parent.on('click', selector, function (event) { var new_tab = event.which === 2 || event.metaKey || event.target.target === '_blank'; properties.url = event.target.href; function callback() { if (new_tab) { return; } window.location = properties.url; } if (!new_tab) { event.preventDefault(); setTimeout(callback, 300); } mixpanel.track(event_name, properties, callback); }); }; 
+7
source

Source: https://habr.com/ru/post/947026/


All Articles