Scripting: Factory Functions

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 dynamically generate widgets using JavaScript functions.

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 https://platform.twitter.com/widgets.js in your page. (See the TFW set-up documentation for a recommended code snippet.)

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 you to work with Twitter content dynamically:

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:

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.
  • options: Optional. An object hash of additional options to configure the widget.

Note that widgets usually render as iframe elements. When an iframe is moved within the DOM the browser will reload its content. For buttons this can waste bandwidth, while for Tweets and timelines this will cause dynamically injected content to be lost. Use the target argument to render widgets into their final location in a page. If you need to delay the display of a widget, use CSS to position the widget off-screen until needed.

Every create function returns a Promise. You can execute code after a widget has been created by passing a callback to:

twttr.widgets.createFoo()
.then(function (element) {
  console.log("Widget created.")
 });

When fulfilled, the promise will pass a reference to a newly created widget element to the chained callback.

Examples:

Create a share button for a URL:

twttr.widgets.createShareButton(
  'https://dev.twitter.com/',
  document.getElementById('new-button'),
  {
    count: 'none',
    text: 'Sharing a URL using the Tweet Button'
  }).then(function (el) {
    console.log("Button created.")
  });

Create a Follow button for a user:

twttr.widgets.createFollowButton(
  'endform',
  document.getElementById('new-button'),
  {
    size: 'large'
  }).then(function (el) {
    console.log("Follow button created.")
  });

Options

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

Additional configuration for all widgets
OptionValuesDefaultNotes
dnttrue, falsefalseEnable Do Not Track for this widget.
hashtagsA comma-separated list of hashtags.UndefinedA list of hashtags to be appended to default Tweet text where appropriate.
langAn ISO 639-1 language code.enThe language in which to render a widget, if supported (see the Translation Center.)
relatedAny comma-separated list of valid Twitter screen names.UndefinedA list of Twitter screen names to be suggested for following after a Tweet is posted.
viaAny valid Twitter screen name.UndefinedA Twitter user mentioned in the default Tweet text as /via @user where appropriate.
Additional configuration for button widgets
OptionValuesDefaultNotes
alignleft, rightlocale 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.
countnone, horizontal, verticalhorizontalShare button and Follow button only. (Vertical count only available for share buttons.)
counturlA valid URL.UndefinedIf 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.)
sizemedium, largemedium
textAny stringUndefinedThe 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. (This should be provided as a String, since Twitter IDs are generated from 64-bit integers, and JavaScript integers are limited to 53 bits.)
  • target: Required. The element in which to render the widget.
  • options: Optional. A hash of additional options to configure the widget.

Examples:

Create an embedded Tweet for a Tweet from the US Department of Interior:

twttr.widgets.createTweet(
  '511181794914627584',
  document.getElementById('first-tweet'),
  {
    align: 'left'
  })
  .then(function (el) {
    console.log("@ev's Tweet has been displayed.")
  });

Options

Additional options for embedded Tweets.
OptionValuesDefaultNotes
alignleft, right, centerUndefinedFloat 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.
conversationnone, allallFor 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.
cardshidden, visiblevisibleToggle whether to render expanded media through Twitter Cards in Tweets. Also applies to images uploaded to Twitter.
widthNumeric valueauto, derived from container size.Fix the width of the embedded widget.
linkColorHexidecimal colour value, e.g. #cc0000Default blue, varies by theme.Adjust the color of links inside the widget.
themedark, lightlightToggle the default colorscheme of the widget.

Timelines

createTimeline takes the data source definition for a timeline. Additional arguments are consistent with embedded Tweets.

Arguments

  • data source: Required. The data source definition for the content that should hydrate the widget.
  • target: Required. The element in which to render the widget.
  • options: Optional. A hash of additional options to configure the widget.

Examples:

Create a timeline widget:

twttr.widgets.createTimeline({
  sourceType: "profile",
  screenName: "twitterdev"
}, 
document.getElementById('timeline'),
{
  width: '450',
  height: '700',
  related: 'twitterdev,twitterapi'
}).then(function (el) {
  console.log("Embedded a timeline.")
});

Data Source

The data source definition describes what content will hydrate the embedded timeline. There are 6 types of data sources: profile, likes, collections, lists, URLs, and widget configurations.

Profile

To power an embedded timeline with Tweets from an individual user, use a profile data source. To do so, set sourceType to profile and set one of screenName or userId.

Options for profile data source.
OptionValuesDefaultNotes
sourceTypeprofileN/A
screenNameAny valid Twitter screen nameUndefined
userIdAny valid Twitter user IDUndefined
twttr.widgets.createTimeline({
  sourceType: "profile",
  screenName: "twitterdev"
}, 
document.getElementById('timeline'));
Likes

To power an embedded timeline with an individual Twitter user’s likes, use a likes data source. To do so, set sourceType to likes and set one of screenName or userId.

Options for likes data source.
OptionValuesDefaultNotes
sourceTypelikesN/A
screenNameAny valid Twitter screen nameUndefined
userIdAny valid Twitter user IDUndefined
twttr.widgets.createTimeline({
  sourceType: "likes",
  screenName: "twitterdev"
}, 
document.getElementById('timeline'));
Collection

To power an embedded timeline with Tweets from a collection, use a collection data source. To do so, set sourceType to collection and set id to the ID of the collection.

Options for collection data source.
OptionValuesDefaultNotes
sourceTypecollectionN/A
idAny valid Twitter collection idUndefined
twttr.widgets.createTimeline({
  sourceType: "collection",
  id: "393773266801659904"
}, 
document.getElementById('timeline'));
List

To power an embedded timeline with a Twitter list, use a list data source. To do so, set sourceType to list and set both ownerScreenName and slug or id.

Options for list data source.
OptionValuesDefaultNotes
sourceTypelistN/A
ownerScreenNameAny valid Twitter screen nameUndefinedShould be used with slug
slugThe string identifier for a list, as used in the URL twitter.com/benward/example-listUndefinedShould be used with ownerScreenName
idAny valid Twitter list idUndefined
twttr.widgets.createTimeline({
  sourceType: "list",
  ownerScreenName: "twitter",
  slug: "official-twitter-accts"
}, 
document.getElementById('timeline'));
URL

To power an embedded timeline with Twitter content that you have the URL for, use a URL data source. To do so, set sourceType to url and set url to the permalink of the Twitter content. Supported content includes profiles, likes, lists, and collections.

Options for URL data source.
OptionValuesDefaultNotes
sourceTypeurlN/A
urlThe permalink to one of a profile, likes timeline, list, or collection.Undefined
twttr.widgets.createTimeline({
  sourceType: "url",
  url: "https://twitter.com/twitterdev/likes"
}, 
document.getElementById('timeline'));
Widget Configuration

To power an embedded timeline with a timeline widget configuration, use a widget configuration data source. To do so, set sourceType to widget and set id to the ID of the widget configuration.

Options for widget configuration data source.
OptionValuesDefaultNotes
sourceTypewidgetN/A
idAny valid Twitter widget idUndefined
twttr.widgets.createTimeline({
  sourceType: "widget",
  id: "123456"
}, 
document.getElementById('timeline'));

Options

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

Additional options for embedded Timelines.
OptionValuesDefaultNotes
ariaPolitepolite, assertive, rudepoliteApply the specified aria-polite behavior to the rendered timeline.
heightNumeric value600Fix the height of the embedded widget.
borderColorHexidecimal colour value, e.g. #cc0000Default grey, varies by theme.Adjust the color of borders inside the widget.
chromenoheader, nofooter, noborders, transparent, noscrollbarUndefinedToggle the display of design elements in the widget. This parameter is a space-separated list of values.
tweetLimit1-20UndefinedRender a timeline statically, displaying only n number of Tweets.
screenNameAny valid Twitter screen nameUndefinedOverride the timeline source with this user’s Tweets.
userIdAny valid Twitter user IDUndefined
showRepliestrue, falsefalseWhen overriding a user timeline, include Tweets that are in reply to to other users.
favoritesScreenNameAny valid Twitter screen nameUndefinedOverride the timeline source with favourite Tweets from this user.
favoritesUserIdAny valid Twitter user IDUndefined
listOwnerScreenNameAny valid Twitter screen nameUndefinedOverride the timeline source with Tweets from a list owned by this user. Must be used in combination with listId or listSlug.
listOwnerIdAny valid Twitter user IDUndefined
listIdAny valid Twitter list IDUndefinedOverride the timeline source with Tweets from this list. Must be used in combination with listOwnerId or listOwnerScreenName.
listSlugThe string identifier for a list, as used in the URL twitter.com/benward/example-list.Undefined

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


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.