Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active October 18, 2016 04:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save itzikbenh/a0211bdaecd3b1c65dfb409fc850a905 to your computer and use it in GitHub Desktop.
Save itzikbenh/a0211bdaecd3b1c65dfb409fc850a905 to your computer and use it in GitHub Desktop.
Twitter share on text highlight. Inspired by theguardian.com. Tested on latest Chrome, Firefox, and Safari.
<!-- Add this anywhere in the page. It assumes your content is inside an <article> tag. -->
<a class="floating-twitter-share-link" href="#" title="Share this" target="_blank">
<i class="fa fa-twitter floating-twitter-share"></i>
</a>
(function($) {
var text = '';
function getText(e) {
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var oRange = window.getSelection().getRangeAt(0);
var oRect = oRange.getBoundingClientRect(); // returns the size of an element and its position relative to the viewport.
var twitter_url = "https://twitter.com/intent/tweet?";
var url = window.location.href;
if(text.length > 0) {
$(".floating-twitter-share").css({"visibility": "visible", "top": (oRect.top - 40)+"px", "left": oRect.left+"px", opacity: 0}).animate({opacity: 1.0},200);
twitter_url += "url="+encodeURIComponent(url);
twitter_url += "&via=yourtwitterhandler&"; // Add your twitter handler here
twitter_url += "text="+encodeURIComponent(text);
$(".floating-twitter-share-link").attr("href", twitter_url);
} else {
$(".floating-twitter-share").animate({opacity: 0.0}, 200, function(){
$(".floating-twitter-share").css({"visibility": "hidden", "top": "0px", "left": "0px"});
});
}
}
$("article").on("mouseup", function(e) {
getText();
})
//
$(document).on("click, mousedown", function(e) {
//Checks that the artcle container is not an ancestor and then hide the twitter icon.
if(!$(e.target).closest('article').length) {
$(".floating-twitter-share").animate({opacity: 0.0}, 200, function(){
$(".floating-twitter-share").css({"visibility": "hidden", "top": "0px", "left": "0px"});
});
}
})
})(jQuery);
.floating-twitter-share {
box-shadow: 0 1px 3px 0 rgba(0,0,0,.2), 0 1px 1px 0 rgba(0,0,0,.14), 0 2px 1px -1px rgba(0,0,0,.12);
width: 40px;
height: 40px;
padding: 10px;
border-radius: 50%;
font-size: 20px;
color: $white;
background: #2EA3F2;
visibility: hidden;
position: fixed;
z-index: 9999999999;
text-align: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment