Add setCaret to WCF.js
authorTim Düsterhus <duesterhus@woltlab.com>
Sat, 20 Oct 2012 11:44:02 +0000 (13:44 +0200)
committerTim Düsterhus <duesterhus@woltlab.com>
Sat, 20 Oct 2012 11:44:09 +0000 (13:44 +0200)
wcfsetup/install/files/js/WCF.js

index a86a5ebcf42206bcc7b4c2eb96d11f3dca1942c1..7f9249beec4318f999d7cb009e81b97377a14abf 100755 (executable)
@@ -338,6 +338,42 @@ $.fn.extend({
                return $position;
        },
        
+       /**
+        * Sets the caret position of current element. If the element
+        * does not equal input[type=text], input[type=password] or
+        * textarea, false is returned.
+        * 
+        * @param       integer         position
+        * @return      boolean
+        */
+       setCaret: function (position) {
+               if (this.getTagName() == 'input') {
+                       if (this.attr('type') != 'text' && this.attr('type') != 'password') {
+                               return false;
+                       }
+               }
+               else if (this.getTagName() != 'textarea') {
+                       return false;
+               }
+               
+               var $element = this.get(0);
+               
+               // set focus to enable caret on this element
+               this.focus();
+               if (document.selection) { // IE 8
+                       var $selection = document.selection.createRange();
+                       $selection.moveStart('character', position);
+                       $selection.moveEnd('character', 0);
+                       $selection.select();
+               }
+               else if ($element.selectionStart || $element.selectionStart == '0') { // Opera, Chrome, Firefox, Safari, IE 9+
+                       $element.selectionStart = position;
+                       $element.selectionEnd = position;
+               }
+               
+               return true;
+       },
+       
        /**
         * Shows an element by sliding and fading it into viewport.
         *