title: Set caret to end of textbox on focus
body: <p><strong>The Question:</strong></p>
  
  <p>When a certain textbox receives focus, set the caret to the end of the textbox. The solution needs to work with IE7, Opera, Chrome and Firefox.<br>
  To make things a bit easier, this behavior is only needed when the current value of the textbox is a fixed value. (Say 'INIT')</p>
  
  <p><strong>Incomplete Solutions:</strong></p>
  
  <p>One would expect this to be pretty simple but I couldn't find an answer on SO that works on all browsers. The following answers do <em>NOT</em> work:</p>
  
  <pre><code>$("#test").focus(function() {
    // This works for Opera only
    // Also tested with $(this).val($(this).val());
    if (this.value == "INIT") {
      this.value = "";
      this.value = "INIT";
    }
  });
  
  $("#test").focus(function() {
    // This works for IE and for Opera
    if (this.value == "INIT") {
      setCaretPosition(this, 4);
    }
  });
  </code></pre>
  
  <p>I got the setCaretPosition function from SO questions and saw it on different blogs aswell:</p>
  
  <pre><code>function setCaretPosition(ctrl, pos) {
          if (ctrl.setSelectionRange) {
              //ctrl.focus(); // can't focus since we call this from focus()
              // IE only
              ctrl.setSelectionRange(pos, pos);
          }
          else if (ctrl.createTextRange) {
              // Chrome, FF and Opera
              var range = ctrl.createTextRange();
              range.collapse(true);
              range.moveEnd('character', pos);   // Also tested with this
              range.moveStart('character', pos); // and this line in comment
              range.select();
          }
  }
  </code></pre>
  
  <p><strong>Fiddle</strong></p>
  
  <p>I've setup a <a href="http://jsfiddle.net/SwRAu/" rel="nofollow">jsFiddle</a>.</p>