<h3>Select text in the paragraphs below and see a pop-up menu.</h3>
<article>
<h1>The Hart and the Hunter</h1>
<p>The Hart was once drinking from a pool and admiring the noble figure he made there.</p>
<p>“Ah,” said he, “where can you see such noble horns as these, with such antlers! I wish I had legs more worthy to bear such a noble crown; it is a pity they are so slim and slight.”</p>
<p>At that moment a Hunter approached and sent an arrow whistling after him.</p>
<p>Away bounded the Hart, and soon, by the aid of his nimble legs, was nearly out of sight of the Hunter; but not noticing where he was going, he passed under some trees with branches growing low down in which his antlers were caught, so that the Hunter
had time to come up.</p>
<p>“Alas! alas!” cried the Hart: “We Often Despise What Is Most Useful To Us.”</p>
</article>
<template id="shareBoxTemplate"><span id="shareBox"><button></button></span></template>
#shareBox {
width: 30px;
height: 30px;
position: absolute;
}
#shareBox > button {
width: 100%;
height: 100%;
background-color: #292A2B;
border: none;
border-radius: 2px;
outline: none;
cursor: pointer;
background-image: url("https://raw.githubusercontent.com/hongkiat/selected-text-action-menu/gh-pages/twitter.png");
background-repeat: no-repeat;
background-position: center;
background-size: 70%;
}
#shareBox > button::after {
position: absolute;
content: '';
border-top: 10px solid #292A2B;
border-left:10px solid transparent;
border-right: 10px solid transparent;
left: 5px;
top: 30px;
}
article{
width: 400px;
margin: auto;
font-size: 14pt;
}
h1,
h3{
text-align: center;
}
h3{
background-color: teal;
color: white;
padding: 5px 0;
font-weight: 400;
}
document.addEventListener('mousedown', onMouseDown);
document.addEventListener('mouseup', onMouseUp);
var temp = document.querySelector('#shareBoxTemplate');
function onMouseDown() {
document.getSelection().removeAllRanges();
var shareBox = document.querySelector('#shareBox');
if (shareBox !== null)
shareBox.remove();
}
function onMouseUp() {
var sel = document.getSelection(),
txt = sel.toString();
if (txt !== "") {
var range = sel.getRangeAt(0);
if (range.startContainer.parentElement.parentElement.localName === "article" || range.startContainer.parentElement.localName === "article") {
document.body.insertBefore(document.importNode(temp.content, true), temp);
var rect = range.getBoundingClientRect();
var shareBox = document.querySelector('#shareBox');
shareBox.style.top = `calc(${rect.top}px - 38px)`;
shareBox.style.left = `calc(${rect.left}px + calc(${rect.width}px / 2) - 30px)`;
var shareBtn = shareBox.querySelector('button');
shareBtn['shareTxt'] = txt;
shareBtn.addEventListener('mousedown', onShareClick, true);
}
}
}
function onShareClick() {
window.open(`https://twitter.com/intent/tweet?text=${this.shareTxt}`);
this.remove();
document.getSelection().removeAllRanges()
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.