Techniques » Select code in snippets with jQuery

This tutorial will show we use jQuery to create “Select Code” links in our Code Sippets.

Before jumping into this jQuery technique, you may want to see our tutorial on how we construct our Consistent Cross-Browser Code Snippets.

Building on our Code Snippet technique we add some HTML, namely a wrapping <div> and a <span> that holds our Select Code link.

[Select Code]

<div><span class="CODEselect">[<a href="#">Select Code</a>]</span>
<pre><code>
<!-- Place Code Here -->
</code></pre>
</div>

We style and hide our <span> with some CSS.

[Select Code]

.CODEselect {
  display: none;
}

.CODEselect a:hover{
  color: #F66;
  text-decoration:underline;
}

We add a layer of javascript and jQuery to the mix. This javascript is attributed to david_kw from this post on codingforums.com. The Select Code links won’t work without javascript and jQuery, so we let jQuery make the links visible with the .show() call, for those users with javascript enabled. Then we set the .click() event of the links to fire the javascript function through a little jQuery Traversing to find the correct Code Snippet area to select.

[Select Code]

function CODEselect(thisID){
  var thisCODE = document.getElementById(thisID);
  if (window.getSelection) {
    var selection = window.getSelection();
    if (selection.setBaseAndExtent) { /* for Safari */
      selection.setBaseAndExtent(thisCODE, 0, thisCODE, 1);
    } else { /* for FF, Opera */
      var range = document.createRange();
      range.selectNodeContents(thisCODE);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  } else { /* for IE */
    var range = document.body.createTextRange();
    range.moveToElementText(thisCODE);
    range.select();
  }
}
$(document).ready(function(){
  $('.CODEselect').show();
  $('.CODEselect a').click(function () {
      var ParentTagName = $(this).parents().get(1).tagName;
      var CodeBoxID = $(this).closest(ParentTagName).find('code').attr('id');
      CODEselect(CodeBoxID);
      return false;
    });
});

Post your thoughts below…


Similar Posts:

Leave a Reply