Friday 23 September 2011

How to catch TAB key press with JavaScript in Firefox,Safari,Opare & IE

<html>
<head>
<script type="text/javascript">
var obj;
var TAB = 9;
function catchTAB(evt,elem)
{
  obj = elem;
  var keyCode;
  if ("which" in evt)
  {// NN4 & FF &amp; Opera
    keyCode=evt.which;
  } else if ("keyCode" in evt)
  {// Safari & IE4+
    keyCode=evt.keyCode;
  } else if ("keyCode" in window.event)
  {// IE4+
    keyCode=window.event.keyCode;
  } else if ("which" in window.event)
  {
    keyCode=evt.which;
  } else  {    alert("the browser don't support");  }


  if (keyCode == TAB)
  {
    obj.value = obj.value + "\t";
    alert("TAB was pressed");
    setTimeout("obj.focus()",1);// the focus is set back to the text input
  }
}
</script>
</head>
<body>
<input type="text" onkeydown="catchTAB(event,this);">
</body>
</html>

1 comment:

  1. Hi Dipankar,
    I am trying this code..but ia m not able to catch the any key press.

    ReplyDelete