Enfocado, haz un enfoque personalizado en el área de texto

Mi código:

$('#myTextArea').one('focus', function() {
     $('#myTextArea')[0].selectionStart = 2;
     $('#myTextArea')[0].selectionEnd = 6;
     $('#myTextArea')[0].focus();
});

The code works fine, on focus (only once), it selects from index 2 to 6.

The problem: since this function is called on focus, it does the custom focus, but then it calls focus AGAIN and I lose focus of the selected text. Any possible solution?

preguntado el 09 de enero de 11 a las 08:01

Try defining the focus function as empty? That might work. Just like $("#myTextArea").focus(function(){}); -

2 Respuestas

I'm not exactly sure why this works but I think it might just do the trick:

$('#myTextArea').bind("focus mousedown", "click", function(event) {
    event.preventDefault();
    $(this).select();
    this.selectionStart = 2;
    this.selectionEnd = 6;
});

Pruébelo aquí.

Respondido el 09 de enero de 11 a las 12:01

The binding made it work! btw, preventDefault() and .select() are unnecessary, it works without them :) - el mal Reiko

Just to clarify: This works because it's acting on the click instead of the focus event. Tabbing to the textarea (which is effectively the focus event without the click) doesn't make the selection. - Kevin

Also, beware that .selectionStart y .selectionEnd isn't completely cross-browser compatible. - Kevin

Since you're already binding to the focus event and you aren't preventing the default behavior, you shouldn't need to fire .focus() manually. Try this instead:

$('#myTextArea').one('focus', function(event) {
     event.preventDefault();
     this.selectionStart = 2;
     this.selectionEnd = 6;
});

Respondido el 09 de enero de 11 a las 11:01

it does the custom focus, but then it automatically-immediately do the default focus, which cause the textarea to lose my custom focus. Is there a way to prevent the default focus? - el mal Reiko

I updated my answer with event.preventDefault(), give that a whirl! - Kevin

You added the event argument to the callback function, too, right? e.g. ...function(event) {... - Kevin

Yes, it didn't do any effect :( - el mal Reiko

Seems you're right. I can do the effect selecting text in another textarea, but not the one being focused. Odd. - Kevin

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.