The Wayback Machine - https://web.archive.org/web/20130910200311/https://dev.twitter.com/docs/tfw-javascript

JavaScript Interfaces for Twitter for Websites

Updated on Sat, 2013-07-13 16:30

By using Twitter Javascript, you agree to the Developer Rules of the Road.

If you're integrating your site with Twitter using Twitter for Websites and Web Intents, you can enhance your application using JavaScript functions and events.

Twitter for Websites products—Tweet buttons, Follow buttons, embedded Tweets and timelines—are all loaded using a JavaScript utility named widgets-js. When adding a Twitter widget to your page, this JavaScript file is included in the HTML embed code, or you can directly include http://platform.twitter.com/widgets.js in your page, using the following code:

  1. window.twttr = (function (d,s,id) {
  2.   var t, js, fjs = d.getElementsByTagName(s)[0];
  3.   if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
  4.   js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
  5.   return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
  6. }(document, "script", "twitter-wjs"));

By default, widgets-js will find mark-up in a page and convert basic, functional mark-up into rich interactive widgets. In addition, there are a number of functions of widgets-js that allow developers to work with Twitter content dynamically, after the page has loaded:

Initializing embedded content after a page has loaded

If content is dynamically loaded into a page (such as when using a pushState technique to navigate between articles), it's necessary to initialize TFW widgets contained within that content. To do this, use the twttr.widgets.load() function.

Called without argument, widgets-js will again search the entire document.body for uninitialized widgets. For better performance, pass either an HTMLElement object, or an array of HTMLElement objects to restrict the search only to children of those nodes.

Example initializing widgets within a single element:

  1. PJAX.fetch('/news/1234', function (newArticleElement) {
  2.   twttr.widgets.load(newArticleElement);
  3.   document.body.replaceNode(newArticleElement, oldArticleElement);
  4. });

Example initializing widgets within an array of elements:

  1. PJAX.fetch('/summaries?since_id=1234', function (arrayOfSummaryElements) {
  2.   twttr.widgets.load(arrayOfSummaryElements);
  3.   arrayOfSummaryElements.forEach(function (el) {
  4.     document.body.appendChild(el);
  5.   }
  6. });

Creating widgets at run-time with factory functions

Widgets can be generated at run-time, without requiring an HTML embed code. A set of factory functions can generate any widget type:

  • twttr.widgets.createShareButton
  • twttr.widgets.createFollowButton
  • twttr.widgets.createHashtagButton
  • twttr.widgets.createMentionButton
  • twttr.widgets.createTimeline
  • twttr.widgets.createTweet

Buttons

createShareButton, createFollowButton, createHashtagButton, and createMentionButton take similar arguments.

Primary Argument

The first argument is required, and is unique to the button type. Provide a string representing one of:

  • url: The URL to be shared.
  • screen_name: The screen_name of a user to be followed, or mentioned.
  • hashtag: Hashtag to be Tweeted and displayed on the button.

Additional Arguments:

  • target: Required. The element in which to render the widget.
  • callback: Optional. A function called after the element is rendered into the page.
  • options: Optional. A hash of additional options to configure the widget.

Examples:

Create a share button for a URL:

  1. twttr.widgets.createShareButton(
  2.   'http://benward.me',
  3.   document.getElementById('new-button'),
  4.   function (el) {
  5.     console.log("Button created.")
  6.   },
  7.   {
  8.     count: 'none',
  9.     text: 'Sharing a URL using the Tweet Button'
  10.   }
  11. );

Create a Follow button for a user:

  1. twttr.widgets.createShareButton(
  2.   'endform',
  3.   document.getElementById('new-button'),
  4.   function (el) {
  5.     console.log("Follow button created.")
  6.   },
  7.   {
  8.     size: 'large'
  9.   }
  10. );

Options

Additional configuration and options can be passed to the factory functions, as in the above examples.

Additional configuration for all widgets
Option Name Values Default Notes
dnt true, false false Enable Do Not Track for this widget.
hashtags A comma-separated list of hashtags. Undefined A list of hashtags to be appended to default Tweet text where appropriate.
lang An ISO 639-1 language code. en The language in which to render a widget, if supported (see the Translation Center.)
related Any comma-separated list of valid Twitter screen names. Undefined A list of Twitter screen names to be suggested for following after a Tweet is posted.
via Any valid Twitter screen name. Undefined A Twitter user mentioned in the default Tweet text as /via @user where appropriate.
Additional configuration for button widgets
Option Name Values Default Notes
align left, right locale dependent (left or right, depending on the text direction of the language.) The alignment of the button within an iframe; use this to ensure flush layout when aligning buttons against opposite edges of your grid.
count none, horizontal, vertical horizontal Share button and Follow button only. (Vertical count only available for share buttons.)
counturl A valid URL. Undefined If the canonical URL to be counted is different from the URL to be shared, you can provide this URL to reference the count. (Share button only.)
size medium, large medium
text Any string Undefined The default, highlighted text a user sees in the Tweet Web Intent.

Tweets

createTweet takes the ID for a Tweet, and then the same additional arguments as for buttons.

Arguments

  • tweetId: The ID of a Tweet to be rendered.
  • target: Required. The element in which to render the widget.
  • callback: Optional. A function called after the element is rendered into the page.
  • options: Optional. A hash of additional options to configure the widget.

Examples:

Create an embedded Tweet for @jack's first Tweet:

  1. twttr.widgets.createTweet(
  2.   '20',
  3.   document.getElementById('first-tweet'),
  4.   function (el) {
  5.     console.log("@jack's Tweet has been displayed.")
  6.   },
  7.   {
  8.     align: 'left'
  9.   }
  10. );

Options

Additional options for embedded Tweets.
Option Name Values Default Notes
align left, right, center Undefined Float the embedded Tweet to the left or right so that text wraps around it, or align center so it floats in the middle of a paragraph.
conversation none, all all For Tweets that are replies, the previous Tweet in the thread will be displayed by default. Use none to hide the thread and show a Tweet alone.
cards none, all all Toggle whether to render expanded media through Twitter Cards in Tweets. Also applies to images uploaded to Twitter.
width Numeric value auto, derived from container size. Fix the width of the embedded widget.
linkColor Hexidecimal colour value, e.g. #cc0000 Default blue, varies by theme. Adjust the color of links inside the widget.
theme dark, light light Toggle the default colorscheme of the widget.

Timelines

createTimeline takes the ID for a timeline, as obtained by first creating a timeline in your widget settings. Additional arguments are consistent with embedded Tweets.

Arguments

  • widgetId: The ID of a timeline widget to be rendered.
  • target: Required. The element in which to render the widget.
  • callback: Optional. A function called after the element is rendered into the page.
  • options: Optional. A hash of additional options to configure the widget.

Examples:

Create a timeline widget:

  1. twttr.widgets.createTimeline(
  2.   '123456',
  3.   document.getElementById('timeline'),
  4.   function (el) {
  5.     console.log("Embedded a timeline.")
  6.   },
  7.   {
  8.     width: '450',
  9.     height: '700',
  10.     related: 'benward,endform,brianellin'
  11.   }
  12. );

Options

All the parameters described above for all widgets and for embedded Tweets apply also to embedded timelines.

Additional options for embedded Timelines.
Option Name Values Default Notes
ariaPolite polite, assertive, rude polite Apply the specified aria-polite behaviour to the rendered timeline.
height Numeric value 600 Fix the height of the embedded widget.
borderColor Hexidecimal colour value, e.g. #cc0000 Default grey, varies by theme. Adjust the color of borders inside the widget.
chrome noheader, nofooter, noborders, transparent, noscrollbar Undefined Toggle the display of design elements in the widget. This parameter is a space-separated list of values.
tweetLimit 1-20 Undefined Render a timeline statically, displaying only n number of Tweets.
screenName Any valid Twitter screen name Undefined Override the timeline source with this user's Tweets.
userId Any valid Twitter user ID Undefined
showReplies true, false false When overriding a user timeline, include Tweets that are in reply to to other users.
favoritesScreenName Any valid Twitter screen name Undefined Override the timeline source with favourite Tweets from this user.
favoritesUserId Any valid Twitter user ID Undefined
listOwnerScreenName Any valid Twitter screen name Undefined Override the timeline source with Tweets from a list owned by this user. Must be used in combination with listId or listSlug.
listOwnerId Any valid Twitter user ID Undefined
listId Any valid Twitter list ID Undefined Override the timeline source with Tweets from this list. Must be used in combination with listOwnerId or listOwnerScreenName.
listSlug The string identifier for a list, as used in the URL twitter.com/benward/example-list. Undefined

For more information on the options for customising embedded Timelines refer to Embedded Timelines.

Web Intent Events

If you're integrating your site with Twitter using Web Intents or Twitter for Websites widgets, Web Intent Events provide the easiest way to integrate feedback in your application, and measure user interaction with intents.

By adding listeners to the actions users perform in Web Intents, you can trigger functionality in your app, and easily send data about those events to your web analytics provider (like Google Analytics and Omniture) or to your own analytics engine.

The Intent Event Object

When a detectable action occurs within a Web Intent or widget, an object representing the event is passed to your JavaScript callback. Intent Event objects respond to the following methods:

Intent event object
Method Return Format Example Values
type A String noting the type of event that occurred "click", "favorite", "tweet", "retweet", "follow"
target A DOM node reference to an HTML element or IFRAME. This value will correspond to the original inciting DOM element. Use this value to differentiate between different intents or buttons on the same page.
region A String indicating whether the user clicked a Tweet Button, Follow Button, Tweet Count, or Screen Name on Tweet Button or Follow Button integrations. "tweet", "count", "follow", "screen_name"
data A JavaScript object with key/value pairs relevant to the Web Intent just actioned Possible key values include: "tweet_id", "source_tweet_id", "screen_name", and "user_id"

Intent Events

You can bind a callback function to each of these events. Events are triggered when the underlying action is successfully completed by the user. Some Web Intents may result in multiple event triggers — for instance, both the "tweet" and "follow" intent events would trigger if a user used the Tweet Button to issue a tweet, and then followed a related account at the end of the flow.

Waiting for Asynchronous Resources

Loading the widgets.js file asynchronously will require you to wait before binding events. You will need to wrap your event bindings in a callback function which will be invoked once everything has loaded. All event examples below assume you have wrapped those event bindings in this callback.

  1. twttr.ready(function (twttr) {
  2.   // bind events here
  3. });

tweet

This event will be triggered when the user publishes a Tweet (either new, or a reply) through the Tweet Web Intent.

  1. twttr.events.bind('tweet', function (event) {
  2.   // Do something there
  3. });

follow

This event will populate the followed user_id in the event object's data argument.

  1. twttr.events.bind('follow', function (event) {
  2.   var followed_user_id = event.data.user_id;
  3.   var followed_screen_name = event.data.screen_name;
  4. });

retweet

This event will populate the original Tweet that was retweeted's source_tweet_id in the event object's data argument.

  1. twttr.events.bind('retweet', function(event) {
  2.     var retweeted_tweet_id = event.data.source_tweet_id;
  3. });

favorite

This event will populate the favorited tweet_id in the event object's data argument.

  1. twttr.events.bind('favorite', function(event) {
  2.     var favorited_tweet_id = event.data.tweet_id;
  3. });

click

Receive an event when the user invokes a Web Intent from within an embedded widget.

Example: Detectable Events for Web Analytics

It's easy to capture these events and pipe them to your web analytics solution. Please note that you'll need to be using HTTP or HTTPs protocols on the hosting page for these events.

  1. // Log any kind of Web Intent event to Google Analytics
  2. // Category: "twitter_web_intents"
  3. // Action: Intent Event Type
  4. // Label: Identifier for action taken: tweet_id, screen_name/user_id, click region
  5.  
  6. // First, load the widgets.js file asynchronously
  7. window.twttr = (function (d,s,id) {
  8.   var t, js, fjs = d.getElementsByTagName(s)[0];
  9.   if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
  10.   js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
  11.   return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
  12. }(document, "script", "twitter-wjs"));
  13.  
  14. // Define our custom event handlers
  15. function clickEventToAnalytics (intentEvent) {
  16.   if (!intentEvent) return;
  17.   var label = intentEvent.region;
  18.   pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);
  19. }
  20.  
  21. function tweetIntentToAnalytics (intentEvent) {
  22.   if (!intentEvent) return;
  23.   var label = "tweet";
  24.   pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);
  25. }
  26.  
  27. function favIntentToAnalytics (intentEvent) {
  28.   tweetIntentToAnalytics(intentEvent);
  29. }
  30.  
  31. function retweetIntentToAnalytics (intentEvent) {
  32.   if (!intentEvent) return;
  33.   var label = intentEvent.data.source_tweet_id;
  34.   pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);
  35. }
  36.  
  37. function followIntentToAnalytics (intentEvent) {
  38.   if (!intentEvent) return;
  39.   var label = intentEvent.data.user_id + " (" + intentEvent.data.screen_name + ")";
  40.   pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);
  41. }
  42.  
  43. // Wait for the asynchronous resources to load
  44. twttr.ready(function (twttr) {
  45.   // Now bind our custom intent events
  46.   twttr.events.bind('click', clickEventToAnalytics);
  47.   twttr.events.bind('tweet', tweetIntentToAnalytics);
  48.   twttr.events.bind('retweet', retweetIntentToAnalytics);
  49.   twttr.events.bind('favorite', favIntentToAnalytics);
  50.   twttr.events.bind('follow', followIntentToAnalytics);
  51. });

Supplemental Events Resources and Examples


These functions make it possible to integrate Twitter user's content into your site dynamically in a JavaScript application, and integrate user interactions into your own application experience.

Please ask questions and share your code and examples in the developer forum. You may also refer to the main Twitter for Websites documentation.