Reputation: 113
I using a keyup event for tab. But fore some reason the code only runs with other keycodes like 38,40,13 . By pressing tab it just does the default tab action and ignores the code. Please help.
dom.live('keyup', function (e) {
var newDom = $(this);
var suggestionpageCount = newDom.attr('data-counter');
if ((e.keyCode == 38) || (e.keyCode == 40)) {
..some code here
}
else if (e.keyCode == 13) {
..some code here
}
else if (e.keycode == 9) {
..some code here
}
I also tried to add it on dom.live('keydown', function (e) but its not working too..
So I noticed that when the cursor is focused on textbox, keyup/keydown function doesn't worked for tab key. do you have any ideas? Thanks
Upvotes: 2
Views: 7352
Reputation: 2796
What you need to do is listen to the keydown on the parent and delegate the event downwards, the tab key's default behaviour is to change element focus meaning the keyup happens on the next element on the page.
$('textarea').parent().on('keydown', 'textarea', function(e) {
if (e.keyCode === 9) {
e.preventDefault();
console.log('Tab key pressed');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>
On a separate note, try using a switch
instead of lots of if/else
statements. They're easier to read and generally out-perform if's/else's
Upvotes: 3