Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture the click of the Twitter "Tweet" button using jQuery

I have the following code on my site, which when it accesses Twitter's API generates it's own markup.

I'm looking to call a JavaScript function on the onClick even of this but, but as the markup changes it seems it's not as simple as just adding an onClick to the anchor.

How can I capture the click of the 'Tweet' button?

<div class="social_button twitter_button">
  <a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal">
    Tweet
  </a>
  <script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
</div>
like image 733
crmpicco Avatar asked Aug 01 '12 10:08

crmpicco


1 Answers

You can't handle click events on this element, because it's in an iFrame, however twitter gives you the opportunity to bind events to the button.

Example: http://jsfiddle.net/ZwHBf/2/ Docs: https://dev.twitter.com/docs/intents/events

Code: HTML:

<div class="social_button twitter_button">
    <div id="foo">
        <a href="https://google.com" class="twitter-share-button" data-count="horizontal">
    Tweet
  </a>
    </div>
    <script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
    <script type="text/javascript" charset="utf-8">
        window.twttr = (function (d, s, id) {
            var t, js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.src = "//platform.twitter.com/widgets.js";
            fjs.parentNode.insertBefore(js, fjs);
            return window.twttr || (t = {
                _e: [],
                ready: function (f) {
                    t._e.push(f)
                }
            });
        }(document, "script", "twitter-wjs"));
    </script>
</div>​

JS:

twttr.events.bind('click', function(event) {
    console.log('clicked');
});​
like image 140
Robin Drexler Avatar answered Sep 19 '22 17:09

Robin Drexler