Estes dias me surgiu a necessidade de colocar o cursor no inicio do campo input para um formulário de login onde o usuário é o email da empresa, então todo login ficaria:
[ |@emailempresa.com
O pipeline ali no início é o cursos, no caso.
Bom, como uso jQuery para tudo, só precisava criar a lógica para isto, foi onde pesquisei na internet e descobri como poderia fazer, logo segue abaixo o plugin para tal.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<div>
<strong>Usuário/email</strong>
<input type="text" id="usuario" />
<input type="button" id="botao" value="Testar Foco" />
</div>
<script type="text/javascript">
jQuery(
function() {
$('#botao').click(
function() {
$('#usuario').val('@emailempresa.com');
$('#usuario').focus().posicaoCursor(0);
}
);
}
);
/**
* Plugin jQuery.posicaoCursor.js
*/
( function( $ ){
$.fn.posicaoCursor = function( posicao ) {
return this.each(function() {
var $this = $( this );
if ( $this.get(0).setSelectionRange ) {
$this.get(0).setSelectionRange( posicao, posicao );
} else if ( $this.get(0).createTextRange ) {
var intervalo = $this.get(0).createTextRange();
intervalo.collapse( true );
intervalo.moveEnd('character', posicao);
intervalo.moveStart('character', posicao);
intervalo.select();
}
});
};
})( jQuery );
</script>
</body>
</html>