Monday, December 26, 2011

Indent Text Using Tab Key In Text Area With jQuery


Indent Text Using Tab Key In Text Area With jQuery
Keith

Have you ever had one of those times when you just wish that you could just use the Tab key to indent your text instead of having it move your cursor onto the next form element? Well, now you won't have to worry about it because this jQuery tutorials snippet will fix that.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>

<script language="javascript">
$(document).ready(function(e) {

  // Using the <TAB>
  $('textarea.tab').keydown(function(e) {
    if(e.keyCode == 9) {
      var start = $(this).get(0).selectionStart;
      $(this).val($(this).val().substring(0, start) + "\t" + $(this).val().substring($(this).get(0).selectionEnd));
      $(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 1;
      return false;
    }
  });

  // Using Spaces
  $('textarea.space').keydown(function(e) {
    if(e.keyCode == 9) {
      var start = $(this).get(0).selectionStart;
      $(this).val($(this).val().substring(0, start) + "    " + $(this).val().substring($(this).get(0).selectionEnd));
      $(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 4;
      return false;
    }
  });
});
</script>

<h5>Using the &lt;TAB&gt;</h5>
<textarea cols="40" rows="10" class="tab"></textarea>
<h5>Using Spaces</h5>
<textarea cols="40" rows="10" class="space"></textarea>

</body>
</html>

============
KEITH FRIAS sees himself as an artist whose talent is in a state of coma, and a tech gadget freak who also loves to dabble in photography.

1 comment: