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:
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="https://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"));
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:
- Late initialization of widgets
- Factory methods for dynamic widgets
- Web Intent events for user actions
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:
PJAX.fetch('/news/1234', function (newArticleElement) { twttr.widgets.load(newArticleElement); document.body.replaceNode(newArticleElement, oldArticleElement); });
Example initializing widgets within an array of elements:
PJAX.fetch('/summaries?since_id=1234', function (arrayOfSummaryElements) { twttr.widgets.load(arrayOfSummaryElements); arrayOfSummaryElements.forEach(function (el) { document.body.appendChild(el);}
});
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:
twttr.widgets.createShareButton('http://benward.me',
document.getElementById('new-button'), function (el) { console.log("Button created.")},
{
count: 'none', text: 'Sharing a URL using the Tweet Button'}
);
Create a Follow button for a user:
twttr.widgets.createShareButton('endform',
document.getElementById('new-button'), function (el) { console.log("Follow button created.")},
{
size: 'large'}
);
Options
Additional configuration and options can be passed to the factory functions, as in the above examples.
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. |
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:
twttr.widgets.createTweet('20',
document.getElementById('first-tweet'), function (el) { console.log("@jack's Tweet has been displayed.")},
{
align: 'left'}
);
Options
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:
twttr.widgets.createTimeline('123456',
document.getElementById('timeline'), function (el) { console.log("Embedded a timeline.")},
{
width: '450', height: '700', related: 'benward,endform,brianellin'}
);
Options
All the parameters described above for all widgets and for embedded Tweets apply also to 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.
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:
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.
twttr.ready(function (twttr) {// bind events here
});
tweet
This event will be triggered when the user publishes a Tweet (either new, or a reply) through the Tweet Web Intent.
twttr.events.bind('tweet', function (event) {// Do something there
});
follow
This event will populate the followed user_id
in the event object's data argument.
twttr.events.bind('follow', function (event) { var followed_user_id = event.data.user_id; var followed_screen_name = event.data.screen_name; });
retweet
This event will populate the original Tweet that was retweeted's source_tweet_id
in the event object's data argument.
twttr.events.bind('retweet', function(event) { var retweeted_tweet_id = event.data.source_tweet_id; });
favorite
This event will populate the favorited tweet_id
in the event object's data argument.
twttr.events.bind('favorite', function(event) { var favorited_tweet_id = event.data.tweet_id; });
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.
// Log any kind of Web Intent event to Google Analytics
// Category: "twitter_web_intents"
// Action: Intent Event Type
// Label: Identifier for action taken: tweet_id, screen_name/user_id, click region
// First, load the widgets.js file asynchronously
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="https://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"));// Define our custom event handlers
function clickEventToAnalytics (intentEvent) { if (!intentEvent) return; var label = intentEvent.region; pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);}
function tweetIntentToAnalytics (intentEvent) { if (!intentEvent) return; var label = "tweet"; pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);}
function favIntentToAnalytics (intentEvent) { tweetIntentToAnalytics(intentEvent);}
function retweetIntentToAnalytics (intentEvent) { if (!intentEvent) return; var label = intentEvent.data.source_tweet_id; pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);}
function followIntentToAnalytics (intentEvent) { if (!intentEvent) return; var label = intentEvent.data.user_id + " (" + intentEvent.data.screen_name + ")"; pageTracker._trackEvent('twitter_web_intents', intentEvent.type, label);}
// Wait for the asynchronous resources to load
twttr.ready(function (twttr) {// Now bind our custom intent events
twttr.events.bind('click', clickEventToAnalytics); twttr.events.bind('tweet', tweetIntentToAnalytics); twttr.events.bind('retweet', retweetIntentToAnalytics); twttr.events.bind('favorite', favIntentToAnalytics); twttr.events.bind('follow', followIntentToAnalytics); });
Supplemental Events Resources and Examples
- Google Analytics Event Tracking Guide
- Twitter Intent Events with Google Analytics using _gaq.push(); by @nulluk
- An optimized approach to Google Analytics integration by @yahelc
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.