Gautam
Gautam

Reputation: 1740

Bind click of tab key with some function using jquery

I need to bind my tab key to a particular function. i.e. whenever i press tab key it should perform a particular function.

What I have done is

$('body').on('keydown', '.myClass :visible:input:enabled:first', function (e) {
    if ((e.which == 9) || (e.keyCode == 9)) {
        $('.myClass :visible:input:enabled:first').focus();
    }
});

this is working fine with no issues in functionality. however, this is making the page performance to take a hit, since with every key hit, this function would be called. I was thinking to find any way to bind click of only tab key, so that this code should run only when a tab key is hit and should ignore all other key presses.

Upvotes: 2

Views: 739

Answers (1)

Vandesh
Vandesh

Reputation: 6894

How can you detect WHAT key is pressed untill you DETECT that a key is pressed? :)

What you can do to optimize is something like -

var myNameSpace = function(){

this.selector = '.myClass :visible:input:enabled:first';

this.myElement = $(selector);

this._body = $('body');
var _self= this;

this._body.on('keydown',_self.selector,function(e){
     if ((e.which == 9) || (e.keyCode == 9)) {
        _self.myElement.focus();
     }
   });
};

The general idea being to 'cache' the node to be accessed. No need to traverse the DOM again and again for just selecting.

Upvotes: 1

Related Questions