firstly Try
$("pre").keydown(function(e){
if (e.keyCode==9) {
e.preventDefault();
$("pre").append("\t");
}
});
for inserting a tab. it will insert a tab after your cursor
then in chrome
var myselection = document.getSelection();
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
in IE8
var myselection = document.selection;
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
should get you caret at the end.
(all together)
$("pre").keydown(function(e){
if (e.keyCode==9) {
e.preventDefault();
$("pre").append("\t");
var myselection = null;
if(document.getSelection)
{
myselection = document.getSelection();
}
else if (document.selection)
{
myselection = document.selection;
}
if(myselection != null)
{
myselection.extend(jQuery("pre")[0].lastChild, jQuery("pre")[0].lastChild.length)
myselection.collapseToEnd();
}
}
});
EDIT
it would also be safer to add in a test to see if the lastChild is null and other such. Also in the keydown function jQuery("pre")
would be better to be jQuery(this)
and put into a variable if you are using more than once. (which the example is but I'm too lazy)