It's the onmouseup event that is causing the selection to get unselected, so you just need to add:
$("#souper_fancy").mouseup(function(e){
e.preventDefault();
});
$('#randomfield').focus(function(event) {
setTimeout(function() {$('#randomfield').select();}, 0);
});
This works fine for input type="text" elements. What kind of element is #souper_fancy?
$("#souper_fancy").focus(function() {
$(this).select();
});
Just preventing default on mouseup causes the text selection to be ON at all times. The MOUSEUP event is responsible to clear the text selection. However, by preventing its default behaviour, you are unable to deselect the textusing the mouse.
To avoid that and get the text selection to work again, you can set a flag on FOCUS, read it from MOUSEUP and reset it so future MOUSEUP events will work as expected.
$("#souper_fancy").focus(function() {
$(this).select();
//set flag for preventing MOUSEUP event....
$this.data("preventMouseUp", true);
});
$("#souper_fancy").mouseup(function(e) {
var preventEvent = $this.data("preventMouseUp");
//only prevent default if the flag is TRUE
if (preventEvent) {
e.preventDefault();
}
//reset flag so MOUSEUP event deselect the text
$this.data("preventMouseUp", false);
});
While this works for selecting it in IE, Firefox, Chrome, Safari, and Opera, it won't let you edit it by clicking a second time in Firefox, Chrome, and Safari. Not entirely sure, but I think this may be due to those 3 browsers re-issuing a focus event even though the field already has focus thus never allowing you to actually insert the cursor (since you're selecting it again), whereas in IE and Opera it appears it isn't doing that so the focus event didn't get fired again and thus the cursor gets inserted.
I found a better fix in this Stack post that doesn't have that problem and works in all browsers.
This should work also in chrome:
$("#souper_fancy").focus(function() {
var tempSouper = $(this);
setTimeout(function(){
tempSouper.select();
},100);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With