alvaro-prieto
9/27/2019 - 8:23 AM

polyfills polifills cursor seleccion seleccionar selection position

//mover el cursor de un input a la posición indicada
if( !jQuery.fn.setCursorPosition ) jQuery.fn.setCursorPosition = function(position){
	if(this.lengh == 0) return this;
	return $(this).setSelection(position, position);
}

//obtener la posición del cursor
if( !jQuery.fn.getCursorPosition ) jQuery.fn.getCursorPosition = function(){
	if(this.lengh == 0) return -1;
	return $(this).getSelectionStart();
}

//obtenemos la selección de un input
if( !jQuery.fn.getSelection ) jQuery.fn.getSelection = function(){
	if(this.lengh == 0) return -1;
	var s = $(this).getSelectionStart();
	var e = $(this).getSelectionEnd();
	return this[0].value.substring(s,e);
}

//obtenemos el inicio de  selección de un input
if( !jQuery.fn.getSelectionStart ) jQuery.fn.getSelectionStart = function(){
	if(this.lengh == 0) return -1;
	input = this[0];
	
	var pos = input.value.length;
	
	if (input.createTextRange) {
		var r = document.selection.createRange().duplicate();
		r.moveEnd('character', input.value.length);
		if (r.text == '') 
			pos = input.value.length;
		pos = input.value.lastIndexOf(r.text);
	} else if(typeof(input.selectionStart)!="undefined")
		pos = input.selectionStart;
	
	return pos;
}

//obtenemos el final de selección de un input
if( !jQuery.fn.getSelectionEnd ) jQuery.fn.getSelectionEnd = function(){
	if(this.lengh == 0) return -1;
	input = this[0];
	var pos = input.value.length;
	if (input.createTextRange) {
		var r = document.selection.createRange().duplicate();
		r.moveStart('character', -input.value.length);
		if (r.text == '') 
			pos = input.value.length;
		pos = input.value.lastIndexOf(r.text);
	} else if(typeof(input.selectionEnd)!="undefined")
		pos = input.selectionEnd;
	
	return pos;
}


//establecemos la selección de texto de un input
if( !jQuery.fn.setSelection ) jQuery.fn.setSelection = function(selectionStart, selectionEnd) {
	if(this.lengh == 0) return this;
	input = this[0];
	
	if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	} else if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}
	
	return this;
}