This is JavaScript code used with the jQuery framework so that a user can highlight a section of text on the page and search for it in the site using the existing search page.
The code works by setting a section in the jQuery selector where you want the code to work and the using css to style the search tag. The only other thing to change is the url for the search page.
/* attempt to find a text selection */
function getSelected() {
if(window.getSelection)
{
return window.getSelection();
}
else if(document.getSelection)
{
return document.getSelection();
}
else
{
var selection = document.selection && document.selection.createRange();
if(selection.text)
{
return selection.text;
}
return false;
}
return false;
}
/* create sniffer */
$(document).ready(function() {
var url = 'http://davidwalsh.name/?s={term}', selectionImage;
$('#content-area').mouseup(function(e){
var selection = getSelected();
if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,'')))
{
if(!selectionImage) {
selectionImage = $('').attr({
href: url,
title: 'Click here to learn more about this term',
target: '_blank',
id: 'selection-image'
}).hide();
$(document.body).append(selectionImage);
}
selectionImage.attr('href',url.replace('{term}',encodeURI(selection))).css({
top: e.pageY - 30, //offsets
left: e.pageX - 13 //offsets
}).fadeIn();
}
});
$(document.body).mousedown(function(){
if(selectionImage)
{
selectionImage.fadeOut();
}
});
});