Category Archives: Programming

Copy text to your clipboard using Javascript

In my current job, I tend to spend a fair amount of time copying a string of information from a website, and then pasting it to another place. More often than not though, I’m not copying a line of text directly of a page, but rather a conglomerate of information I stick together using other Javascript calls. Because I’m lazy efficient, I relegate all of this to simple “copy” buttons.

This can be achieved using a simple Javascript function:

function copyToClipboard(parentElement, string) {

//parentElement is the containing element, this can be any element, but most browsers default behaviour is to scroll to this element, which isn't a very nice effect
//string is the string you want to copy to the clipboard
var copyDiv = document.createElement('div');
copyDiv.id = "copyDiv";
copyDiv.contentEditable = true;
parentElement.appendChild(copyDiv);
copyDiv.innerHTML = string;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
parentElement.removeChild(copyDiv);

}

You can add this to any element as per normal:

document.getElementById("this").addEventListener("click", function() {

copyToClipboard(this, this.innerHTML);

});

Here is an example that takes a table of first and last names, and copies “X’s last name is Y” to your clipboard.

Jill Smith
Eve Jackson
John Doe

CSS Sliding Background Animation

This is what I use on my Home Page, and achieve a sliding box effect on hover solely using CSS with no jquery.

It uses a background image, a transition, and adjusts the background-position on hover.

An example of the CSS:

#container {

background-size: 200% 100%;
background-image: linear-gradient(to right, white 50%, red 50%);
-webkit-transition: background-position 1s;
-moz-transition: background-position 1s;
transition: background-position 1s;

}
#container:hover {

background-position: -100% 0%;

}


First example - mouse over here

Note that the background-size and background-position are both in {x y} format, so you can change this from left > right sliding to right > left or even vertical. You can also use an actual image for the background-image, and speed up or slow down the transitions by changing the time in the transition property.

#boxTwo{

background-size: 200% 100%;
background-image: linear-gradient(to right, white 50%, red 50%);
-webkit-transition: background-position 1s;
-moz-transition: background-position 1s;
transition: background-position 1s;

}
#boxTwo:hover {

background-position: 100% 0%;

}


Right to Left

#boxThree{

background-size: 100% 200%;
background-image: url("http://www.veganpirate.info/images/DSC00953.JPG");
-webkit-transition: background-position 5s;
-moz-transition: background-position 5s;
transition: background-position 5s;

}
#boxThree:hover {

background-position: 0% 100%;

}


Then image will slowly slide down