Skip to content

Instantly share code, notes, and snippets.

@kakakazuma
Last active August 29, 2015 14:06
Show Gist options
  • Save kakakazuma/c9f128330e291c4849f3 to your computer and use it in GitHub Desktop.
Save kakakazuma/c9f128330e291c4849f3 to your computer and use it in GitHub Desktop.
「テキストボックスのフォーカス時に選択状態にする」を少しだけクロスブラウザ対応した ref: http://qiita.com/kakakazuma/items/cbf2f523af192e87e059
<input id="test"></input>
var input = document.getElementId("test");
input.onfocus = focusInput;
function focusInput(e) {
if (e) {
(function(e){
setTimeout( function() {setFocus(e);});
})(e);
}
}
function setFocus(e) {
if (e) {
var targetTag = e.target;
targetTag.focus();
//とりあえず全選択、選択範囲指定したいときはbgnとendを適宜指定
var num = targetTag.value.length;
var bgn = 0;
var end = num;
if(typeof(targetTag.selectionStart) != "undefined"){
targetTag.selectionStart = bgn;
targetTag.selectionEnd = end;
} else if(document.selection) {
var range = targetTag.createTextRange();
range.collapse();
range.moveEnd( "character", bgn );
range.moveStart( "character", end );
range.select();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment