views:

118

answers:

2

I have the same problem as the user in this question, which is due to this bug in Webkit. However, the workaround provided will not work for my app. Let me re-state the problem so that you don't have to go read another question:

I am trying to select all the text in a textarea when it gets focus. The following jQuery code works in IE/FF/Opera:

$('#out').focus(function(){
  $('#out').select();
});

However, in Chrome/Safari the text is selected--very briefly--but then the mouseUp event is fired and the text is deselected. The following workaround is offered in the above links:

$('#out').mouseup(function(e){
  e.preventDefault();
});

However, this workaround is no good for me. I want to select all text only when the user gives the textarea focus. He must then be able to select only part of the text if he chooses. Can anyone think of a workaround that still meets this requirement?

+2  A: 

Make a bool. Set it to true after a focus event and reset it after a mouse up event. During the mouse up, if it's true, you know the user just selected the text field; therefore you know you must prevent the mouse up from happening. Otherwise, you must let it pass.

var textFieldGotFocus = false;

$('#out').focus(function()
{
    $('#out').select();
    textFieldGotFocus = true;
});

$('#out').mouseup(function(e)
{
    if (textFieldGotFocus)
        e.preventDefault();
});

$(document).mouseup(function() { textFieldGotFocus = false; });

It's important that you put the mouseup listener that resets the variable on document, since it's not guaranteed that the user will release the mouse button over the text field.

zneak
thanks! this inspired an even simpler idea: instead of a listener on document.mouseup, just set the flag to false on out.mouseup: `if(textFieldGotFocus){ e.preventDefault(); textFieldGotFocus = false;}`
Jenni
+1  A: 

How about this?

$('#out').focus(function () {
    $('#out').select().mouseup(function (e) {
        e.preventDefault();
        $(this).unbind("mouseup");
    });
});
digitalFresh
thanks, i like it even more--no need for a separate flag!
Jenni