Skip to main content
The X for Websites JavaScript library supports dynamic insertion of a Post 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

ParameterDescriptionExample value
urlA share URL, or an empty string if you would not like to include a Post composer URL componenthttps://dev.x.com/
targetElDOM node of the desired parent elementdocument.getElementById('container')
optionsOverride default widget options. See Post 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 Post 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('Post 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.