Thursday, November 22, 2012

JavaScript: Copy & Highlight

As part of my discipline for documenting those functionalities that make me suffer and sweat, I want to leave this short code exemplifying how to make a copy & paste of an element of the DOM, at the same time that it highlights the element.

For the copy part I used a popular library that uses a Flash file as the executor of the operation: ZeroClipboard. The copy operation is not a standard capability of all browsers. That's whay a Flash file is requried. For the highlighting I found a code that works properly in the main browsers (IE, FF, Safari & Chrome). These are the  functions in the below code: "getTextNodesIn" and "setSelectionRange". The entire code below allows the user to click in the text for automatically make a copy to the clipboard, and then show copied text as an alert message. At the end it highlights the text.

<script type="text/javascript" src="ZeroClipboard.min.js"></script>  
<script type="text/javascript">
 function getTextNodesIn(node) {
  var textNodes = [];
  if (node.nodeType == 3) {
  } else {
   var children = node.childNodes;
   for (var i = 0, len = children.length; i < len; ++i) {
    textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
  return textNodes;

 function setSelectionRange(el, start, end) {
  if (document.createRange && window.getSelection) {
   var range = document.createRange();
   var textNodes = getTextNodesIn(el);
   var foundStart = false;
   var charCount = 0, endCharCount;

   for (var i = 0, textNode; textNode = textNodes[i++]; ) {
    endCharCount = charCount + textNode.length;
    if (!foundStart && start >= charCount
      && (start < endCharCount ||
      (start == endCharCount && i < textNodes.length))) {
     range.setStart(textNode, start - charCount);
     foundStart = true;
    if (foundStart && end <= endCharCount) {
     range.setEnd(textNode, end - charCount);
    charCount = endCharCount;

   var sel = window.getSelection();
  } else if (document.selection && document.body.createTextRange) {
   var textRange = document.body.createTextRange();
   textRange.moveEnd("character", end);
   textRange.moveStart("character", start);;

 function highlight() {
  var element = document.getElementById("span_id");
  setSelectionRange(element, 0, element.innerHTML.length); 

 <span id="span_id">Copy Me!</span>
  ZeroClipboard.setMoviePath( 'ZeroClipboard.swf' );
  var clip = new ZeroClipboard.Client();
  var element = document.getElementById("span_id");
  clip.setText( element.innerHTML )
  clip.glue( 'span_id' ); 
  clip.addEventListener( 'onMouseUp', highlight );

No comments:

Post a Comment