Record Text Selections Using MooTools or jQuery AJAX

Written by David Walsh on Tuesday, November 3, 2009


One technique I’m seeing more and more these days (CNNSI.com, for example) is AJAX recording of selected text. It makes sense — if you detect users selecting the terms over and over again, you can probably assume your visitors are searching that term on Google, Yahoo, etc. I’ve duplicated this functionality using my favorite javascript library, MooTools, and another javascript library, jQuery.

The MooTools Javascript

window.addEvent('domready',function(){
	//gets the selected text
	var getSelection = function() {
		return $try(
			function() { return window.getSelection(); },
			function() { return document.getSelection(); },
			function() { 
					var selection = document.selection && document.selection.createRange();
					if(selection.text) { return selection.text; }
					return false;
		      }
		) || false;
	};
	//event to listen
	var selectRequest = new Request({
		url: 'ajax-selection-copy.php',
		method: 'post'
	});
	$('content-area').addEvent('mouseup',function(e) {
		var selection = getSelection();
		if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
			selectRequest.send('selection=' + encodeURI(selection));
		}
	});
});

The first step is attempting to grab the selected text during the mouseup within our designated container. If we find a text selection we fire an AJAX request to a PHP script which will save the text selection.

The jQuery Javascript

/* 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() {
	$('#content-area').mouseup(function() {
		var selection = getSelected();
		if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
			$.ajax({
				type: 'post',
				url: 'ajax-selection-copy.php',
				data: 'selection=' + encodeURI(selection)
			});
		}
	});
});

The MooTools code translated to jQuery.

The PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && $selection = trim($_POST['selection'])) {
	mysql_query('INSERT INTO text_selections (selection,date_selected) VALUES(\''.mysql_escape_string(stripslashes($selection)).'\',NOW())');
}

The above PHP code is very primitive. Depending on the setup of your system (PHP Framework, security settings, etc.) you will want to implement additional measures to prevent attacks on this script.

Recording text selections is a great way to discover what topics and/or terms your audience is interested in. You may also want to provide more information on these terms within posts.

What are your thoughts on this? Do you think this is too much like Spyjax? Perfectly OK?


Follow via RSS Epic Discussion

php strip_tags(comment_author()) ?> November 03 / #
Alex says:

It’s been some time I haven’t seen something interesting (for my own taste and interests) at here. This can be added in the good category of spyjax techniques :)
Nice one David!

php strip_tags(comment_author()) ?> November 03 / #

Delicious! text selection for the masses. Perhaps I’ll try to find some useful applications for it…

php strip_tags(comment_author()) ?> November 03 / #
Hunter says:

You bring up a good topic on PHP security. I am just getting into PHP and am reading up on writing secure PHP w/MySQL. I read the site below which seems to have some good advice, but I was curious if you had any references you could recommend.

Also, I enjoy this blog as I am just starting out with jQuery.

php strip_tags(comment_author()) ?> November 03 / #
Alex says:

@Hunter
Addison Wesley – Securing PHP Web Applications (2008)
You can buy it on amazon or download it as a warez ebook copy.

php strip_tags(comment_author()) ?> November 03 / #
EmEhRKay says:

Cool stuff. This technique could mimic the nytimes’ website text selection search feature

php strip_tags(comment_author()) ?> November 03 / #
Hunter says:

Thanks Alex! I have to make this comment longer, so I am doing that here.

php strip_tags(comment_author()) ?> November 03 / #
Salva says:

Alex, I don’t know who you are but thanks for using http://www.geekherocomic.com as a link there :-) Salva.

php strip_tags(comment_author()) ?> November 03 / #

Another very useful function, that’s worth sharing!
THX!

php strip_tags(comment_author()) ?> November 03 / #
Jack Watson-Hamblin says:

Hey, I wouldn’t mind turning this into a jQuery plugin, mind if I do, I”ll link back to you if I post it up on the plugins.jquery.com site.

php strip_tags(comment_author()) ?> November 04 / #
Adrien says:

Well, it might be interresting for the coding part.
But if you have a visitor like, you’ll have about a hundred INSERT per page. I select text all the time while I’m reading it. sorry. :/

php strip_tags(comment_author()) ?> November 04 / #
Alex says:

@Hunter && @Salva

You are both welcome guys, and Salva – your webcomic is GREAT!

php strip_tags(comment_author()) ?> November 04 / #
Aleks says:

Awesome script! Thanks David!

php strip_tags(comment_author()) ?> November 05 / #

Wow this very cool script :D BTW let’s me know … why on Safari browser it’s doesn’t work :(

php strip_tags(comment_author()) ?> November 05 / #
aldrin says:

I like the way you did in the php security.. Honestly, I haven’t encounter that code. but It’s very useful. thanks

php strip_tags(comment_author()) ?> November 05 / #

Hey David – I just found your site a couple months ago and have been reading it frequently ever since. I just wanted to comment on your use of mysql_escape_string() there: that function is deprecated in 5.3 and removed in php 6 along with a big note saying that relying on it is highly discouraged.

The proper one to use is mysql_real_escape_string() or my favorite, binding variables with the PDO interface.

Thanks for making such a good site!

David Walsh November 06 / #

@Aleks: Thank you sir!

php strip_tags(comment_author()) ?> November 15 / #
Anthrax says:

Wow you certainly have a great site here and also nice script.

php strip_tags(comment_author()) ?> December 04 / #
nulll says:

Great post! Thanks you gave me a great idea for a UI I must do… grazie!

Be Heard!

I want to hear what you have to say! Share your comments and questions below.

Name*:
Email*:
Website:  


© David Walsh 2007-2009. Contact David Walsh. Powered by the remarkable MooTools javascript framework.