Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript onclick trigger key click (using jQuery)

How can I activate a "left" or "right" keyboard arrow push on click of a div.

So for example

$('.item').click(function(){
    keyCode(37);
});

(I know that 37 is left)

like image 471
rickyduck Avatar asked Dec 28 '22 06:12

rickyduck


2 Answers

You would go like

$('.item').click(function(){
    $( document.body ).trigger({
        type: 'keypress',
        which: 37,
        keyCode: 37
    });
});

You can of course replace document.body with any other node that has a keypress or keydown event bound to it.

Reference: .trigger()

like image 123
jAndy Avatar answered Jan 13 '23 13:01

jAndy


From Definitive way to trigger keypress events with jQuery:

var e = jQuery.Event("keypress");
e.which = 37; // # Some key code value
$("div").trigger(e);
like image 43
paulslater19 Avatar answered Jan 13 '23 13:01

paulslater19