HTML - CSS - JS Twitter Button
by tqbit
HTML
<article>
<h1>Create a Twitter Share button</h1>
<p>Don't want to add lots of additional, third party scripts to your app for a simple feature? Then you might be curious about how to build your own "Share to Twitter" button!</p>
<a href="https://blog.q-bit.me/how-to-create-a-share-to-twitter-button-with-html-css-javascript">Read the article</a>
</article>
<button id="button--twitter" class="btn btn--blue">
<i class="btn__icon">
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Twitter</title><path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/></svg>
</i>
<span class=btn__text>
Share to Twitter!
</span>
</button>
CSS
article {
margin-bottom: 1rem;
}
.btn {
cursor: pointer;
border: none;
border-radius: 4px;
padding: 0.25rem 0.5rem;
display: block;
}
.btn--blue {
background-color: #1DA1F2;
color: #fff;
fill: #fff;
}
.btn__icon * {
display: inline;
height: 1rem;
width: 1rem;
}
.btn__text {
font-size: 1rem;
font-weight: 600;
}
JavaScript
const twitterUrl = "https://twitter.com/intent/tweet/";
const linkTarget = '_top' // try '_blank' here as well
const windowOptions = 'menubar=no,status=no,height=750,width=500'
function extractTitleText() {
return document.querySelector('h1').innerText;
}
function extractAnchorLink() {
return document.querySelector('a').href;
}
function extractWindowLink() {
return window.location.href;
}
function openTwitterWindow(text, link) {
const twitterQuery = `text=${text}&url=${link}`;
return window.open(`${twitterUrl}?${twitterQuery}&`, linkTarget, windowOptions);
}
function registerShareButton() {
const text= extractTitleText()
const link = extractAnchorLink();
const twitterButton = document.querySelector('#button--twitter');
twitterButton.addEventListener('click', () => openTwitterWindow(text, link))
}
registerShareButton()