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.


Parameter Description Example value
url A share URL, or an empty string if you would not like to include a Tweet composer URL component
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' }


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.

    text: 'Hello World'


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.

.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.