Drupal.behaviors.token = function() { // keep track of field focus $('textarea, input[type="text"]').focus(function() { Drupal.settings.tokenlastfocus = this; }); $('span.token-key').each(function(){ var newThis = $(''+ $(this).html() +'').click(function(){ if (typeof Drupal.settings.tokenlastfocus != 'undefined') { var myField = Drupal.settings.tokenlastfocus; var myValue = $(this).text(); //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } $('html,body').animate({scrollTop: $(myField).offset().top}, 500); } return false; }); $(this).replaceWith(newThis); }); }