34

I am creating a custom Tweet button with my own styles however it seems when you opt for customising your own you cannot use the data attributes (data-text, data-url etc.). The utilisation of the data attributes only seem available when you use the Twitter styled button that uses the widget javascript (http://platform.twitter.com/widgets.js).

Here is some code taken from the Twitter dev website. Below is the Tweet button using the data attributes:

<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
<div>
  <a href="http://twitter.com/share" class="twitter-share-button"
    data-url="http://dev.twitter.com/pages/tweet_button"
    data-via="twitterapi"
    data-text="Checking out this page about Tweet Buttons"
    data-related="anywhere:The Javascript API"
    data-count="vertical">Tweet</a>
</div>

Now below here is the 'Build your Own' Tweet button:

<style type="text/css" media="screen">
  #custom-tweet-button a {
    display: block;
    padding: 2px 5px 2px 20px;
    background: url('http://a4.twimg.com/images/favicon.gif') left center no-repeat;
    border: 1px solid #ccc;
  }
</style>
<div id="custom-tweet-button">
  <a href="http://twitter.com/share?url=http%3A%2F%2Fdev.twitter.com%2Fpages%2Ftweet-button" target="_blank">Tweet</a>
</div>

Hopefully that all makes sense...

igneosaur
  • 3,268
  • 3
  • 29
  • 44
  • Hey @igneosaur please click improve if you're gonna use most of my changes, instead of rejecting it :-) – Michael Sørensen Jan 11 '21 at 12:51
  • 1
    @MichaelSørensen Sorry mate, my fault. I was having a look and had an unintentional mouse discharge, clicking the wrong button. Me no work websites good. Couldn't undo so stole the changes off you. I'm an edit stealer. – igneosaur Jan 13 '21 at 16:24

1 Answers1

55

For some reason they won't let you use the Javascript data attributes with a custom button so you have to add them to the URL in your HTML. So for your example:

You would then add &text=your%20text with your text.

<a href="http://twitter.com/share?url=http%3A%2F%2Fdev.twitter.com%2Fpages%2Ftweet-button&text=my%20text%20here" target="_blank">

The other codes are the same, just add &related= etc.

Make sure you replace any spaces with %20 and that is it.

MDCore
  • 17,583
  • 8
  • 43
  • 48
JTP
  • 566
  • 6
  • 3
  • brilliant, but ugly solution. As long as it works! thanks so much. I suppose I should do some preprocessing and dynamically construct the final string. – ahnbizcad Sep 27 '14 at 21:52
  • 3
    this is somewhat outdated, check here for the documentation, you use query strings but this shows how to do things like add hashtags: https://dev.twitter.com/web/tweet-button/web-intent – Alex Podworny Nov 28 '16 at 21:53