开发者

prevent default action for tab key in chrome?

i want to PREVENT the default action when the tab key is pressed and only wanna do it in chrome, 开发者_Python百科i can't find a solution for that, can anyone please help ?

i am using jquery


input.keydown(function(event){
    if (event.keyCode === 9) {
        event.preventDefault();
    }
})

On keyup is too late, you need to call the event on keydown. That worked for me.


Here's an article on how to detect chrome: http://javascriptly.com/2008/09/javascript-to-detect-google-chrome/

And this question: Disable tab key on a specific div might help you on disabling the tab key. If you are able to combine both yourself, you've probably got it working.

The disable function would become something like:

$('.textarea').on('keyup mouseup', function(e) {
  if(e.which == 9) { e.preventDefault(); }
});

e.which = 9 is the tab key according to the last link given. If you are able to wrap the browser detection around it yourself, I guess you've got your working example.


This might be a bit late, but combining @EvgueniNaverniouk's answer and @K._'s comment (on @Joshua_Pendo's answer), it is determined that you must use onkeydown and the more recent event.key instead of event.keyCode. What event.key does is it returns the name of the key instead of the code. For example, the tab key will be returned as "Tab" (This is case sensitive). Here is the finished working code:

function checkForTab(event) {
    if (event.key == "Tab") {
        event.preventDefault();
    }
    else {
        //whatever stuff if not Tab
    }
}
document.getElementById("element").onkeydown = checkForTab(event);

function checkForTab(event) {
	if (event.key == "Tab") {
		event.preventDefault();
        document.getElementById('element').value += " Also notice this text appears every time you press tab!";
	}
	else {
		//whatever stuff if not Tab
	}
}
document.getElementById('element').onkeydown = checkForTab;
//Trick is to use keydown and use event.key instead of keyCode
<textarea id="element" style="width: 300px; height: 100px;">Press tab key here, you'll see default action doesn't occur!</textarea>

Run the Code Snippet above to see an example of what I mean. You can now use a code like this to replace the default action of Tab with the action that adds spaces to a textarea. Note: the reason I use .key instead of .keyCode is because .keyCode is now deprecated as @K._ mentioned. Hope this helps!


JS:

  document.getElementById('message_textarea').addEventListener('keydown', (event) => {
    console.log('tab pressed on message textarea');
    if (event.keyCode === 9) {
      event.preventDefault();
    }
  });

HTML:

<textarea id="message_textarea"></textarea>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜