Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

javascript - Mixpanel track_links does not work with dynamically added elements

I'm having trouble using mixpanel.track_links with links added dynamically (after page load).

For a general example, given 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>

At some user action, links are added to the page using jquery. For example:

$('#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 isn't triggered on click of the newly created link. I'm hoping someone can share their experience in enabling the track_link function to work for dynamically added links.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Example usage: 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);
    });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...