Ajax Loader
×
HTML
<!-- Problem: Cursor inside input should always be present at the end -->
1
<!-- Problem: Cursor inside input should always be present at the end -->
2
 
3
<input type="text" value="hello world foo bar bak baz more text"><br><br>
4
<textarea> 
5
 
6
  hello world
7
  foo bar
8
  bak baz
9
  more text
10
  .
11
</textarea>
 
CSS
body {
1
body {
2
  padding: 50px;
3
  background: whiteSmoke;
4
}
5
 
6
input, textarea {
7
  border: 1px solid lightGray;
8
  padding: 10px;
9
}
10
 
11
textarea {
12
  height: 200px;
13
  width: 300px;
14
}
 
JavaScript
x
51
1
 
2
var input = document.querySelector('input');
3
var textarea = document.querySelector('textarea');
4
 
5
var old_val = '';
6
var reset = function (e) {
7
  
8
  var val = this.value
9
    , len = val.length;
10
  
11
  this.setSelectionRange(len, len);
12
  
13
  // To fix android chrome bug
14
  // although good practise just incase
15
  // user is using some other browser/os combination
16
  // with similar issue.
17
  if (e.type === 'keyup' || e.type === 'keydown') {
18
    var short, long;
19
    if (old_val.length < val.length) {
20
      short = old_val;
21
      long = val;
22
    }
23
    else {
24
      short = val;
25
      long = old_val;
26
    }
27
    
28
    if (long.indexOf(short) !== 0) {
29
      val = old_val;
30
      this.value = val;
31
      this.setSelectionRange(old_val.length, old_val.length);
32
      
33
      e.preventDefault();
34
      // Just exit from the function now
35
      return false;
36
    }
37
  }
38
  
39
  old_val = val;
40
};
41
 
42
input.addEventListener('focus', reset, false);
43
input.addEventListener('mouseup', reset, false);
44
input.addEventListener('keyup', reset, false);
45
input.addEventListener('keydown', reset, false);
46
 
47
textarea.addEventListener('focus', reset, false);
48
textarea.addEventListener('mouseup', reset, false);
49
textarea.addEventListener('keyup', reset, false);
50
textarea.addEventListener('keydown', reset, false);
51
 
 

Stick Caret to End in Input fields and Textareas

CSSDeck G+