Skip to content

Instantly share code, notes, and snippets.

@paradite
Last active January 24, 2023 10:48
Show Gist options
  • Save paradite/f66862dbfb61001c8dd09680747eec06 to your computer and use it in GitHub Desktop.
Save paradite/f66862dbfb61001c8dd09680747eec06 to your computer and use it in GitHub Desktop.
intercept paste and do formatting in JavaScript (in Angular.js)
// tested in Chrome and Firefox
this.onPaste = function (event) {
if($(event.target).is(':focus')) {
// actually typing on the element, stop paste progation to outside paste handler
event.stopPropagation();
// intercept paste and format the text
event.preventDefault();
var newText = (event.originalEvent || event).clipboardData.getData('text/plain');
newText = newText.replace(/\r?\n/g, ' ');
// merged the newly pasted text with original text
var el = $(event.target);
var cursorPosStart = el.prop('selectionStart');
var cursorPosEnd = el.prop('selectionEnd');
var v = el.val();
var textBefore = v.substring(0, cursorPosStart);
var textAfter = v.substring(cursorPosEnd, v.length);
var mergedText = textBefore + newText + textAfter;
// insert text manually by updating model to trigger msd-elastic directive
self.fieldModel = mergedText;
// move cursor to correct position after paste
$timeout(function(){
el[0].selectionStart = el[0].selectionEnd = cursorPosStart + newText.length;
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment