Creating Common Twitter Button For Entire WebSite Using JavaScript

Introduction

This article shows how to create a Twitter button for sharing the dynamically changing divs or dynamically changing URLs. It will be very use full if you want to share any URL on the basis of user viewport. For instance, say you want to share the URL 1 when the user's curser is at div 1 and then the user hits the share button and in response to that we need to share the URL of that div, not of that page. My explanation may sound somewhat ambiguous but don't worry, the example will make clear what I am trying to say.

Simple Twitter Button

Let's say you have a parallax kind of website. Now you decided to put a Twitter share button so that the user can share whatever pages they are viewing. For that you decided to use a Twitter Button. You can place the simple button on your specified page using the following snippet.

<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en">Tweet</a>
 
<script>

!function (d, s, id) {

    var js, fjs = d.getElementsByTagName(s)[0]; if (!d.getElementById(id))

    { js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); }

}(document, "script", "twitter-wjs");

</script>

The code above will create a simple button as shown in the following picture:

a9p1.JPG

To share the URL, simply click on the button and the rest is handled by Twitter itself. Now look at the following picture:

a9p2.JPG

You can customize the URL text and the URL to share by changing the attributes of the anchor tag. For example, check the following code snippet:

a9p3.jpg

Now the output will look like this:

a9p4.JPG

You can check the Twitter resource center for other attributes. So far it has been simple but the article is not for this purpose. Let's talk about the problem in the Twitter Button above.

The Problem

Now let's say you have several divs in one page and want to share the URL of the div on which the user pressed the share button. But since we have only one common Twitter button, it can't share different urls each time because we already gave a value to the data-url attribute. Now you may say that we can change the URL dynamically by using JavaScript (using the setAttribute() method and all) but that's not possible. Twitter is doing some magic behind the scenes. Just check the following picture.

a9p8.jpg

The magic is you created the anchor tag for the Twitter button but after the page is loaded, it is nowhere in the page. If you look at the picture above, you can easily identify that we have an iframe added to our page. Actually that iframe is added by the Twitter button JavaScript. It renders the anchor to IFrame. So that's why we can't change it using simple techniques. So the question is how to change the URL dynamically, in ther words after the page load.

Solution

To solve the preceding problem we need to remove that button completely and we will create our own that will work as we want. We can also change the propertys of the new iFrame but that will be much more troublesome. Before starting we need to prepare the workspace. Either you can open JS Bin or start with the following code.

Preparing the workspace

Just create a new HTML file and place this code in it:

<html>

<head>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.min.css"rel="stylesheet" type="text/css" />

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>

    <meta charset="utf-8" />

    <title>Overlay by Arpit</title>

      <style>

        /* we will use this section for adding css classes or any styling */

    </style>

 </head>

<body>

       <!-- HTML will go here -->

      <script>

          $(document).ready(function () {

              // We will use this for adding our jQuery or scripts

          });

    </script>

</body>

</html>

Replicating the Problem

To solve the problem we need a prototype of that problem. To create a prototype just paste the following HTML into your HTML section.

<div id="block1" onmouseover="share('UploadFile/4aac15/building-accordion-with-css3-without-using-any-jquery-or-js/');">

</div>

<div id="block2" onmouseover="share('UploadFile/4aac15/creating-a-file-uploader-using-javascript-and-html-5/');">

</div>

<div id="block3" onmouseover="share('UploadFile/4b0136/getting-started-with-view-in-mvc-5/');">

</div>

 

In the preceding HTML I'm creating 3 divs and assume that each div has something that you want to share with the common share button. The URL in the share method is the URL of the content. In my case it is different but you may pass the fragment URL also so that when it is clicked, one can easily navigate to that div. Example of URL containing the fragment:

<div id="block2" onmouseover="share('UploadFile/4aac15/creating-a-file-uploader-using-javascript-and-html-5#middleSection');">

The middleSection is the fragment name. Share is a function that we will write later in our article. To give some design just add the following CSS:

#ta{

  position:fixed;

  left:92%;

  top:51%;

  width:50px;

  height:50px;

}

#block1{

 width:100%;

  height:900px;

  background-color:rgba(1,220,3,0.4);

  border:1px solid black;

}

#block2{

 width:100%;

  height:900px;

  background-color:rgba(41,220,130,0.4);

  border:1px solid black;

}

#block3{

 width:100%;

  height:900px;

  background-color:rgba(1,220,123,0.4);

  border:1px solid black;

}

 

The Rgba() function generates the color. The rest of the CSS is quite mediocre. Now let's add the Twitter button to our page; for that add the following HTML snippet.

<a id="ta" href="https://twitter.com/share?url=https%3A%2F%2Fdev.twitter.com%2Fpages%2Ftweet-button" target="_blank">

     <img   src='http://wis.ewi.tudelft.nl/tweetum/twitter.png' height=50 width=50/>

 </a>

It will add the Twitter button with the little blue bird as the icon.

Writing Script and solving the problem

Now it's time to jump into the battlefield and we have JavaScript as our weapon to fight against this problem. To solve this problem we need to use the "query string." In simple words what we need to do is the following.

  1. Get the original query string. For this we can use getAttribute("href") on the anchor element. We named it rawSrc. It looks as in the following picture:
    a9p5.JPG
     
  2. Now we need to find the index of "url=" in the query string. Let's call it is li1 . It contains the index of "url=" in the string.
  3. Now remove the "url=" and all after that from query string and save it. We can use the substring() function for that. Let's call it "backUrl1". It contains the Twitter share URL but without any actual sharing URL.
  4. Now we need to append our own URL in that query string. That is simple, just append the parameter of the share function into backUrl1. Let's call it "newUrl1".
  5. Now for the important task, we need to update the value of the anchor tag href by this new URL. For that we will use the setAttribute() method.   
  6. All the technical work is done. Now let's wrap the entire code into a function call share that accepts the URL to share.

After doing all the preceding steps the script will look like the following snippet:

a9p6.jpg


Live DEMO


a9p9.JPG

Summary

Thanks for reading this article. I tried my best to keep it to the point. The excess code is removed for the sake of simplicity. I also omitted the other parameters in the query string but you can add them in the same way as the preceding one.

Up Next
    Ebook Download
    View all
    Learn
    View all