AleMal
AleMal

Reputation: 2087

jQuery on TAB pressure simulate on(mousedown) event

In my webpage i have to trap TAB key pressure and then simulate mousedown event for the object involved. I tried so:

$('*').keydown(function(e) {
var keyCode = e.keyCode || e.which; 

if (keyCode == 9) { 
    var elementClicked = e.target.nodeName;
    elementClicked.mousedown();
}
});

but error

Uncaught TypeError: undefined is not a function

on elementClicked.mousedown(); row appears.

How can i simulate and call the mousedown event on element involved in TAB pressure??

Thanks in advance

AM

Upvotes: 1

Views: 589

Answers (3)

vsync
vsync

Reputation: 130095

$(this).trigger('mousedown') or just $(this).click() and this will trigger whatever event is bound to that element. note that you should do *... that's super bad for performance.

Try:

$(document).on('keydown.tab', '*', function(e){
  if( e.keyCode == 9 ){
    $(this).trigger('mousedown');
  }
  return false;
});

But you can't really know on which element was the TAB clicked...

UPDATE:

you should first give all elements the attribute tabindex, only then those element could be tracked when pressing the tab key, because they have focus (by clicking on them first or focusing via keyboard) :

$('body *').each(function(i){
    this.setAttribute('tabindex',i);
});

DEMO PAGE - only the h1 element simulates click using TAB

Upvotes: 1

Ashish Panchal
Ashish Panchal

Reputation: 504

May be you should try below updated code:

$(document).on("keyup", function(e) {
    var keyCode = e.keyCode || e.which; 

    if (keyCode == 9) { 
        var elementClicked = $(this);
        elementClicked.trigger("mousedown");
    }
});

Hope this helps!

Upvotes: 0

griffon vulture
griffon vulture

Reputation: 6764

elementClicked is an object name and not an object - select object using jquery:

$(elementClicked).mousedown()

Upvotes: 1

Related Questions