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 using 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.
  1. <a href="https://twitter.com/share" class="twitter-share-button" data-lang="en">Tweet</a>   <script>  
  2. !function (d, s, id) {  
  3.     var js, fjs = d.getElementsByTagName(s)[0]; if (!d.getElementById(id))  
  4.     { js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); }  
  5. }(document, "script""twitter-wjs");  
  6. </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 on 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 other 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 properties 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:
  1. <html>  
  2. <head>  
  3.     <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.min.css"rel="stylesheet" type="text/css" />  
  4.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>  
  6.     <meta charset="utf-8" />  
  7.     <title>Overlay by Arpit</title>  
  8.       <style>  
  9.         /* we will use this section for adding css classes or any styling */  
  10.     </style>  
  11.  </head>  
  12. <body>  
  13.        <!-- HTML will go here -->  
  14.       <script>  
  15.           $(document).ready(function () {  
  16.               // We will use this for adding our jQuery or scripts  
  17.           });  
  18.     </script>  
  19. </body>  
  20. </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.
  1. <div id="block1" onmouseover="share('UploadFile/4aac15/building-accordion-with-css3-without-using-any-jquery-or-js/');">  
  2. </div>  
  3. <div id="block2" onmouseover="share('UploadFile/4aac15/creating-a-file-uploader-using-javascript-and-html-5/');">  
  4. </div>  
  5. <div id="block3" onmouseover="share('UploadFile/4b0136/getting-started-with-view-in-mvc-5/');">  
  6. </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:
  1. <div id="block2" onmouseover="share('UploadFile/4aac15/creating-a-file-uploader-using-javascript-and-html-5#middleSection');">  
  2. 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:  
  3. #ta{  
  4.   position:fixed;  
  5.   left:92%;  
  6.   top:51%;  
  7.   width:50px;  
  8.   height:50px;  
  9. }  
  10. #block1{  
  11.  width:100%;  
  12.   height:900px;  
  13.   background-color:rgba(1,220,3,0.4);  
  14.   border:1px solid black;  
  15. }  
  16. #block2{  
  17.  width:100%;  
  18.   height:900px;  
  19.   background-color:rgba(41,220,130,0.4);  
  20.   border:1px solid black;  
  21. }  
  22. #block3{  
  23.  width:100%;  
  24.   height:900px;  
  25.   background-color:rgba(1,220,123,0.4);  
  26.   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.
  1. <a id="ta" href="https://twitter.com/share?url=https%3A%2F%2Fdev.twitter.com%2Fpages%2Ftweet-button" target="_blank">  
  2.      <img   src='http://wis.ewi.tudelft.nl/tweetum/twitter.png' height=50 width=50/>  
  3.  </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
 
 
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.