Capturing TAB key in text box

Capturing TAB key

I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.

Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?

I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift+Tab, or Ctrl+Q?

Don't forget to check for the focused window, and let it bubble up normally if you are not in the editor textarea

6 Answers

Even if you capture the keydown/keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.

In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF.

<body>
<input type="text" id="myInput">
<script type="text/javascript">
    var myInput = document.getElementById("myInput");
    if(myInput.addEventListener ) {
        myInput.addEventListener('keydown',this.keyHandler,false);
    } else if(myInput.attachEvent ) {
        myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
    }

    function keyHandler(e) {
        var TABKEY = 9;
        if(e.keyCode == TABKEY) {
            this.value += "    ";
            if(e.preventDefault) {
                e.preventDefault();
            }
            return false;
        }
    }
</script>
</body>

I just corrected line 4, from "if (el.attachEvent)" to "if (myInput.attachEvent)"

Notice this code adds TAB only at the end. It's inconvenient in most occasions.

Is there a simple way to remove the spaces again with keycode 8?

only keydown catches tabs, keyup does but after tabbing to an uncertain element

I'd rather tab indentation not work than breaking tabbing between form items.

If you want to indent to put in code in the Markdown box, use Ctrl+K (or ⌘K on a Mac).

In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event callback. This makes life easier for working with multiple browsers.

The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:

document.onkeydown = TabExample;

function TabExample(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var tabKey = 9;
  if(evt.keyCode == tabKey) {
    // do work
  }
}

I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.

A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?

The question is entirely application dependent. I am working on a code editor control. I didn't provide a tab key and my students all complained. I didn't because I didn't want to break accessibility for my one student who was blind. I've now added tab support, but also provided a user preference option to turn it off.

very good point about the accessibility implications.

could you say more about how adding tab key support this might break accessibility for blind users? Is it because some blind users rely on tab to shift focus, like this answer describes?

In Chrome on the Mac, alt-tab inserts a tab character into a <textarea> field.

Here’s one: . Wee!

there is a problem in best answer given by ScottKoon

here is it

} else if(el.attachEvent ) {
    myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}

Should be

} else if(myInput.attachEvent ) {
    myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}

Due to this it didn't work in IE. Hoping that ScottKoon will update code

How to set background color of HTML element using css properties in JS

How to set background color of HTML element

How can I set the background color of an HTML element using css in JavaScript? 17 Answers In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor . function setColor(element, color) { element.style.backgroundColor = color; } // where el is the concerned element var el = document.getElementById('elementId'); setColor(el, 'green'); I'd like to add the color obviously needs to be in quotes element.style.backgroundColor = "color"; for example - element.style.backgroundColor = "orange"; excellent answer In Selenium tests: ((IJavaScriptExecutor)WebDriver).ExecuteScript("arguments[0].style.background = 'yellow';", webElement); @Catto In this case, color is an argument to the function, hence it should not be in quotes. However, you are right that…

Read more…

How can I make the browser see CSS and Javascript changes?

How see CSS and Javascript changes

CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP . NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include…

Read more…

How can I detect if a browser is blocking a popup? - JavaScript

Detect if a browser is blocking a popup

Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly? 9 Answers If you use JavaScript to open the popup, you can use something like this: var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined')…

Read more…