javascript

Adding links to the copied user clipboard text and appending a link to the text – JavaScript – MySql – Ajax –

Add links to user Selected Copied Text

Tynt’s a great product, I like it it has a cool stats page and overall I think it’s a great innovation. Check it out if you don’t know what it does.

I wanted something similar that wasn’t dependent on a 3rd party service that I could play with and tweak and do so privately outside of the view of an external organisation like tynt. My starting point was this which I’ve tweaked a little to serve a purpose or two.

I wanted something that I could modify to my own needs and vary aspects that I considered important.

One of these was link building and another was to see what users were copying to gain additional insights that I might use to improve a project or two.

I wanted to give myself an option to help people share my content in ways that added context to what it was they were writing about or citing the content for and to enable an easy visual way for people to quote the source. Both by URL and a relevant hyperlink.

The methods below help me achieve these objectives.

Quite a few webpages have long page titles that might include brand at the front or back, and probably contain a phrase that’s important to what they’d like to rank for or how they’d like to be linked to.

In this regard, we might have a page that has a page title of “Great Hotels In London – Check out this fab resource of well priced places to stay in London from Hotelprovider”

A user copying a piece of text from a page like that, which employed the system below would, in addition to any copied text see a read more and source option when they pasted the copied text into word, or their blog, or facebook or twitter or email or wherever else it was they were using the copied info.

copied text
Read More:Great Hotels In London.
Source:http://www.theurltheyreferenced.com

We’d achieve this by using a hyphen or “-” as a stop word in the pattern aspect of our addlink() function below.

In this regard everything after the “-” would be truncated. We simply replace “wordintitle” in the function below with “-“.

Where a page title doesn’t have a hyphen, then the whole page title is used instead.

This is where it’s important to know your site structure and of course, desired outcomes.

We also include a #tag or anchor in the embedded url.

In the example I use #copied which I can then reference in my logfiles or other analytics packages.

If you use GA and you don’t want to or can’t go the ?UTM_SOURCE route, then you can enable # anchor tracking and even disable clicks that came from folks using internal anchors. You just got to mess around with your GA code a little.

Step 1 Put in Footer before closing Body tag

<? $permalink=$_SERVER[REQUEST_URI];?>
<script type="javascript/html">
function addLink() {
var mytitle=document.title;
var pattern =" wordintitle ";

/*whatever word you put in the var pattern above will be the text 
that'll form the words in the pasted link 
so if wordintitle was 'horse' then everything before 
the word 'horse' would be used for the anchor text,
 else it'll use the full string of document.title */

mytitle= mytitle.substr(0, mytitle.indexOf(pattern));

if(mytitle === ''){
mytitle=document.title;
}
var selection = window.getSelection(),
pagelink = '<br /><br /> Read More:<a href="'+ document.location.href+'‪#‎copied‬">'
+ mytitle +'</a><br />Source:' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
newdiv.style.background = '‪#‎ffffff‬';
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);

window.setTimeout(function () {
shareTxt(); 
/* only need this if you are putting the info in a db comment it out if 
this is not the case */

//alert('Text Copied For You');
 /*uncomment the line above if you are not using the ajax 
shareTxt function */ 

toggle('copytoclip');

/* you can create a hidden div and put a fadeout notify message
 telling the user that it was copied to the clipboard i'd use
 jquery but it's not mandatory to show a message, 
could do stealth if it suits - if you do not have 
jquery or are happy with a simple alert then comment the 
toggle line out or remove it */

document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);


function shareTxt(){
/* this function sends the data copied to your database for
 later reference */
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var texti = window.getSelection();
var queryString = "?sharetext="+ texti +"&ref=<?=$permalink;?>";
ajaxRequest.open("GET", "shared.php" + queryString, true);
ajaxRequest.send(null);
}

 
function toggle(d)
/* this function shows your hidden div and then hides
 it after 800ths of a second */
{
var o=document.getElementById(d);
o.style.display=(o.style.display=='none')?'block':'none';
$('‪#‎copytoclip‬').fadeOut(800);
}
 
</script>

Step 2 Run this PhpMyadmin or  SQL interpreter and create table

The page that the ajax sends the variables to firstly needs a MYSQL table for the data, so here is some sql below. Place this in to your sql interpreter in phpmyadmin for instance and it will create the necessary table for you.

CREATE TABLE IF NOT EXISTS `copyshared` (
`cid` int(10) NOT NULL AUTO_INCREMENT,
`ref` varchar(255) NOT NULL,
`textshare` varchar(255) NOT NULL,
`ip` varchar(32) NOT NULL,
`opsys` varchar(255) NOT NULL,
`zackmo` varchar(30) NOT NULL,
`hash` int(25) NOT NULL,
UNIQUE KEY `cid` (`cid`),
KEY `ref` (`ref`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;

Step 3 Create a text file and name it shared.php

You’ll need some PHP to process the data and put it into the database. Enter your db credentials in the connection script and save it as shared.php then upload it to the root directory of your site

<? 
/* create a file and call it shared.php */
if($_GET[ref] and $_GET[sharetext] ) {
@ $db = mysql_connect("localhost", "dbuser", "password");
mysql_select_db("dbname");

$txt= mysql_real_escape_string($_GET[sharetext]);
$ref = mysql_real_escape_string($_GET[ref]);
$opsys=$_SERVER[HTTP_USER_AGENT];
$ip=$_SERVER['REMOTE_ADDR'];
$insert="insert into copyshared values ('', '$ref', '$txt', 
'$ip', '$opsys', NOW(), '$hash')";
$qry_result = mysql_query($insert);
}
?>

Step 4 Place in Footer after Javascript closing tag above

If you want to show a message div saying ‘copied to clipboard’ for your users then you can add a div that fades out like this.

<div id="copytoclip" class="ctc" style="padding:3px;position:fixed; display:none;
 bottom:15%; height:auto; margin-left:15%; margin-right:auto; vertical-align:top;
 z-index:5000; vertical-align:top">
<div align=center>
<img src="someniceimage.png"> 
<span style="position:absolute; bottom:25px; left: 0; max-width:100%; color: white;
 font: bold 18px Helvetica, Sans-Serif; letter-spacing: -1px; background: rgb(0, 0, 0);
 /* fallback color */background: rgba(0, 0, 0, 0.7);padding: 10px; ">Copied to Clipboard</span> 
</div>
</div>

It has been tested (and works) on an ipad, a pc and an iphone. I’ve tested it with ie10, firefox, chrome and safari with no issues. I haven’t tried it with a droid phone.

If you decide to use the fade() function then you’ll need to have the jquery library installed (most domains use it these days so you shouldn’t have an issue with it)

Ultimately, there’s nothing to stop people removing the link created or the url, so it might work for good link building and it might not.

The good aspect for me (and this is where tynt might just be an easier option for you) is that I can periodically review what kinds of content snippets people are grabbing and then gain any insights presented.

Install Recap

To install, you need to create the table in phpmyadmin with the sql referenced above and upload/create shared.php on your server and place it in the directory of the domainroot.

You also need to open up a footer file or include you have that goes sitewide and paste the javascript referenced above along with the div content just before the closing body tag.

If you don’t want to do the ajax or db route thing then follow the instructions I’ve put in the code removing or commenting out the div aspect and the shareTxt() function.

That’s it.

css.php
%d bloggers like this: