JavaScript Factory Function

Embedded Tweet JavaScript Factory Function

The Twitter for Websites JavaScript library supports dynamic insertion of embedded Tweets using the twttr.widgets.createTweet function. Pass a Tweet ID, target parent element, and any custom options.

The code snippets on this page assume widgets.js has successfully loaded on your page. Include an asynchronous script loader on your page while initializing window.twttr as described in our JavaScript loader documentation. All JavaScript code depending on widgets.js should execute on or after twttr.ready.

 

Parameter Description Example value
tweetID The numerical ID of the desired Tweet. '20'
targetEl DOM node of the desired parent element. document.getElementById('container')
options Override default widget options. See Embedded Tweet parameter reference for details. { theme: 'dark' }

Example

An element with a DOM ID of container exists on the page.

      <div id="container"></div>
    

The code snippet below will insert Tweet ID 20 into a page inside an element with a unique ID of container. The options object specifies a dark theme customization.

      twttr.widgets.createTweet(
  '20',
  document.getElementById('container'),
  {
    theme: 'dark'
  }
);
    

Promises

The twttr.widgets.createTweet returns a Promise. You can execute code after a widget has been inserted onto your page by passing a callback to the resulting promise’s then function.

      twttr.widgets.createTweet(...)
.then( function( el ) {
  console.log('Tweet added.');
});