OBJECTIVE: "Need to allow the user to select any text in an article Then show a custom menu with a twitter sharing button next to the selected text After clicking the sharing button, the twitter 'sharing window' should appear with the selected text pre-filled, ready to be tweeted" Using Javascript
HTML test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="teststyle.css">
<script src="testjs.js"></script>
<title>Twitter sharing button</title>
</head>
<body>
<article>
<h1>Select over the text below</h1>
<p>Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript. CSS is designed to enable the separation of presentation and content, including layout, colors, and fonts. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics. </p>
</article>
<template><span id="control"></span></template>
</body>
</html>
CSS code teststyle.css
#control {
background-image: url("data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width='40px' height='40px'><foreignObject width='40px' height='40px'><div xmlns='http://www.w3.org/1999/xhtml' style='width:40px;height:40px;line-height:40px;text-align:center;color:transparent;text-shadow: 0 0 yellow, 2px 4px black, -1px -1px black;font-size:35px;'></div></foreignObject></svg>");
cursor: pointer;
position: absolute;
width: 40px;
height: 40px;
}
#control::before{
background-color: black;
color: white;
content: " tweet this! ";
display: block;
font-weight: bold;
margin-left: 37px;
margin-top: 6px;
padding: 2px;
width: max-content;
height: 20px;
}
JavaScript testjs.js
var control = document.importNode(document.querySelector('template').content, true).childNodes[0];
document.querySelector('p').onpointerup = () => {
let selection = document.getSelection(), text = selection.toString();
if (text !== "") {
let rect = selection.getRangeAt(0).getBoundingClientRect();
control.style.top = `calc(${rect.top}px - 48px)`;
control.style.left = `calc(${rect.left}px + calc(${rect.width}px / 2) - 40px)`;
control['text']= text;
document.body.appendChild(control);
}
}
control.addEventListener('pointerdown', oncontroldown, true);
function oncontroldown(event) {
window.open(`https://twitter.com/intent/tweet?text=${this.text}`)
this.remove();
document.getSelection().removeAllRanges();
event.stopPropagation();
}
document.onpointerdown = ()=> {
let control = document.querySelector('#control');
if (control !== null) {control.remove();document.getSelection().removeAllRanges();}
}
I don't get the proper result. What seems to be the problem?