JavaScript Factory Function

Tweet Button JavaScript Factory Function

The Twitter for Websites JavaScript library supports dynamic insertion of a Tweet button using the twttr.widgets.createShareButton function. Pass a share URL, 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.

Arguments

Parameter Description Example value
url A share URL, or an empty string if you would not like to include a Tweet composer URL component https://dev.twitter.com/
targetEl DOM node of the desired parent element document.getElementById('container')
options Override default widget options. See Tweet button parameter reference for details { text: 'Hello world' }

Example

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

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

The code snippet below will create a new Tweet button with pre-selected share text of “Hello world” and a shared URL of “/” inserted into a page inside an element with a unique ID of container.

      twttr.widgets.createShareButton(
  '/',
  document.getElementById('container'),
  {
    text: 'Hello World'
  }
);
    

Promises

The twttr.widgets.createShareButton function 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.createShareButton(...)
.then( function( el ) {
  console.log('Tweet button added.');
});

    

Hashtag, mention buttons

Create a hashtag or mention button using the twttr.widgets.createHashtagButton and twttr.widgets.createMentionButton functions respectively. The same object applies.