How to Code a “Click to Tweet” Button

Default avatar.
July 05, 2019

Having users share your content online is a great way to grow your brand. In this tutorial we’ll cover everything you need to know to add a simple link to your page, so that users can tweet it directly.

How to Code a “Click to Tweet” Button.

With Instagram, Snapchat and other “young” social media platforms taking over the internet, Twitter still remains one of the most popular marketing channels.

It has around 326 million active users per month which means that your target audience is likely using it. This is why you should at least consider using it as a marketing channel for your business. Having Twitter as one of the main marketing channels is not only going to help build awareness of your brand but can also drive traffic to your website and make your articles go viral.

How can this be achieved? Well, it’s a pretty straightforward tactic that some of the top bloggers are using. The idea is that within your blog post you have short pieces of content that are catchy and people like them. Those pieces of content can then be easily tweeted. (For example, it could be a quote from someone who is an authority in your niche, or a statistic that you feel is likely to be shared by your visitors.)

So, let me show you how you can have “click to tweet” buttons added automatically to every quote in your article.

Before we get started, let me say that this is a medium-advanced technique. If you’re using WordPress you can use a ready-to-go plugin that will serve the same purpose.

Creating “Click to Tweet” Buttons with JavaScript

Let’s assume that we want to turn from this article about conferences that says “According to webdesignerdepot.com ...” into a tweetable block.

Given that we have the following html structure:

<article id="article">
<blockquote> I only ever go to marketing conferences to meet new people and listen to their experiences. Those people never include the speakers, who are generally wrapped up in their own world and rarely give in the altruistic sense. </blockquote>
</article>

Here is how we would create a click to tweet button:

Step 1

We need to collect all the <quote> and <blockquote> elements from our article when the document loads:

document.addEventListener("DOMContentLoaded", function() {
 // Step 1. Get all quote elements inside the article
 const articleBody = document.getElementById('article');
 const quotes = [...articleBody.querySelectorAll('quote, blockquote')];

Step 2

Create additional variables to store the current page url, tweetable url and a ‘click to tweet’ button:

 let tweetableUrl = "";
 let clickToTweetBtn = null;
 const currentPageUrl = window.location.href;

Step 3

We need to iterate over all the quote elements that we want to make tweetable and append a “click to tweet button” for each of them:

 quotes.forEach(function (quote) {
 // Create a tweetable url
 tweetableUrl = makeTweetableUrl(
 quote.innerText, currentPageUrl
 );

 // Create a 'click to tweet' button with appropriate attributes
 clickToTweetBtn = document.createElement("a");
 clickToTweetBtn.innerText = "Click to Tweet";

 clickToTweetBtn.setAttribute("href", tweetableUrl);
 clickToTweetBtn.onclick = onClickToTweet;

 // Add button to every blockquote
 quote.appendChild(clickToTweetBtn);

 }); 
});

Step 4

Add 2 missing functions: makeTweetableUrl, that will create a tweetable URL, and onClickToTweet that will act as our event listener and open a window for the tweet (once the button is clicked):

function makeTweetableUrl(text, pageUrl) {
 const tweetableText = "https://twitter.com/intent/tweet?url=" + pageUrl + "&text=" + encodeURIComponent(text);
 return tweetableText;
}

function onClickToTweet(e) {
 e.preventDefault();

 window.open(
 e.target.getAttribute("href"),
 "twitterwindow", 
 "height=450, width=550, toolbar=0, location=0, menubar=0, directories=0,scrollbars=0"
 );

}

Here it is working on CodePen.

Creating “Click to Tweet” Buttons with jQuery

Now, let me show you a slightly different way to get the same result that you can implement if you’re using jQuery.

Here is the code:

$(document).ready(function() {

 // Get all quote elements inside the article
 const articleBody = $("#article");
 const quotes = articleBody.find("quote, blockquote");
 let tweetableUrl = "";
 let clickToTweetBtn = null;

 // Get a url of the current page 
 const currentPageUrl = window.location.href;

 quotes.each(function (index, quote) {
 const q = $(quote);
 // Create a tweetable url
 tweetableUrl = makeTweetableUrl(
 q.text(), currentPageUrl
 );

 // Create a 'click to tweet' button with appropriate attributes
 clickToTweetBtn = $("<a>");
 clickToTweetBtn.text("Click to Tweet");

 clickToTweetBtn.attr("href", tweetableUrl);
 clickToTweetBtn.on("click", onClickToTweet);

 // Add button to every blockquote
 q.append(clickToTweetBtn);

 });
});

function makeTweetableUrl(text, pageUrl) {
 const tweetableText = "https://twitter.com/intent/tweet?url=" + pageUrl + "&text=" + encodeURIComponent(text);
 return tweetableText;
}

function onClickToTweet(e) {
 e.preventDefault();
 window.open(
 e.target.getAttribute("href"),
 "twitterwindow", 
 "height=450, width=550, toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
 );
}

As you can see, the code is the same, except that it takes advantage of jQuery’s functions to simplify the code we have to write. Here’s the jQuery version working on CodePen.

Conclusion

As you can see, creating a “click to tweet” button doesn’t require much time but it can be a great way to encourage your visitors to share your content on Twitter.

I hope this tutorial was helpful and you learned something new. Feel free to use this piece of code and implement it on your website.

Featured image via DepositPhotos.

Andriy Haydash

Andriy Haydash is a founder of PROGMATIQ web design agency. He specializes in building websites for small business owners to help them build and grow their brand online.

Read Next

15 Best New Fonts, September 2024

Welcome to our roundup of the best new fonts we’ve found on the web in the previous four weeks. In this month’s edition…

3 Essential Design Trends, October 2024

This article is brought to you by Constantino, a renowned company offering premium and affordable website design You…

A Beginner’s Guide to Using BlueSky for Business Success

In today’s fast-paced digital world, businesses are always on the lookout for new ways to connect with their audience.…

The Importance of Title Tags: Tips and Tricks to Optimize for SEO

When it comes to on-page SEO, there’s one element that plays a pivotal role in both search engine rankings and user…

20 Best New Websites, September 2024

We have a mixed bag for you with both minimalist and maximalist designs, and single pagers alongside much bigger, but…

Exciting New Tools for Designers, September 2024

This time around we are aiming to simplify life, with some light and fast analytics, an all-in-one productivity…

3 Essential Design Trends, September 2024

September's web design trends have a fun, fall feeling ... and we love it. See what's trending in website design this…

Crafting Personalized Experiences with AI

Picture this: You open Netflix, and it’s like the platform just knows what you’re in the mood for. Or maybe you’re…

15 Best New Fonts, August 2024

Welcome to August’s roundup of the best fonts we’ve found over the last few weeks. 2024’s trend for flowing curves and…

Turning Rejection into Fuel: Your Guide to Creative Resilience

Rejection sucks. And for some reason, it’s always unexpected, which makes it feel like an ambush. Being creative is…

20 Best New Websites, August 2024

The overarching theme in this selection is simplicity. Minimalism never really goes out of fashion and with good…

Free AI-Website Builder, Scene, Helps With the Worst Part of Site Design

AI website design platform, Scene As we’ve been hearing constantly for the last couple of years, AI will soon replace…