Skip to content

Instantly share code, notes, and snippets.

@mmcclimon
Created December 10, 2013 20:36
Show Gist options
  • Save mmcclimon/7898371 to your computer and use it in GitHub Desktop.
Save mmcclimon/7898371 to your computer and use it in GitHub Desktop.
Quick jQuery script to tweet the highlighted text on a page.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<p>This is the text. You'll need to make sure jQuery is loaded. When
you highlight some text we use some JavaScript to grab it and update
the tweet button.</p>
<p>The tweet button (copy this &lt;a&gt; link and the next script tag verbatim):
<span id='tweet-span'>
<a href="https://twitter.com/share" id='tweet'
class="twitter-share-button"
data-lang="en"
data-count='none'>Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</span></p>
<script>
// this is the part that actually does the work
function tweetSetup(text) {
if (twttr === undefined) { return; }
if (text === undefined) { text = ''; }
var tweet = $('<a>')
.attr('href', "https://twitter.com/share")
.attr('id', "tweet")
.attr('class', "twitter-share-button")
.attr('data-lang', "en")
.attr('data-count', "none")
.attr('data-text', text)
.text('Tweet');
$(".twitter-share-button").remove();
$("#tweet-span").prepend(tweet);
twttr.widgets.load();
}
$('body').mouseup(function(evt) {
evt.preventDefault();
var t = window.getSelection().toString();
if (t !== '') { tweetSetup(t) }
});
</script>
</body>
</html>
@kshaffer
Copy link

Awesome, thanks! I'll try it out. I'm thinking this could be great for social reading of online texts. Where would I add a default hashtag to the code? (I don't know JavaScript, other than that it works on GitHub Pages. :) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment