Jack
Jack

Reputation: 2771

jquery keyboard navigation from specific input text box

I am working on an internal web application, and would like to add keyboard navigation to it. From researching, some form of javascript seemed like the best way to handle this.

Here is an example of what I came up with:

   $(document).keydown(function (e) {

                if (e.keyCode == 74) {
                    window.location = 'page1.html'; // Key = J
                }
                else if (e.keyCode == 75) {
                    window.location = 'page2.html'; // Key = k
                }
                else if (e.keyCode == 76) {
                    window.location = 'page3.html'; // Key = L
                }

            });

This works fine, but I would like to make it executable only from 1 specific text input. (Basically a navigation box) I haven't been able to figure that part out. Any ideas?

Does anyone have experience with this form of navigation. Is it reliable?

I am not very experienced with javascript, so any thoughts or suggestions are appreciated.

Upvotes: 1

Views: 768

Answers (4)

sanchez
sanchez

Reputation: 4530

   $(document).keydown(function (e){

        if( e.target.id !== "elementId" ){
            return;
        }

        if (e.keyCode == 74) {
            window.location = 'page1.html'; // Key = J
        }
        else if (e.keyCode == 75) {
            window.location = 'page2.html'; // Key = k
        }
        else if (e.keyCode == 76) {
            window.location = 'page3.html'; // Key = L
        }
    }); 

Upvotes: 1

Sindhara
Sindhara

Reputation: 1473

First it is recommended to use e.which instead of e.keyCode as far as I know.

$('#id_of_input').on('keydown',function(e){...});

$(document).on('keydown','#id_of_input',function(e){});

The second one should be used when the element is dynamically added to the page.

Upvotes: 0

putvande
putvande

Reputation: 15213

You should bind the event to your specific field to do that. Something like this:

$('#yourinputfieldid').on('keydown',function (e) {
    if (e.keyCode == 74) {
        window.location = 'page1.html'; // Key = J
    } else if (e.keyCode == 75) {
        window.location = 'page2.html'; // Key = k
    } else if (e.keyCode == 76) {
        window.location = 'page3.html'; // Key = L
    }
});

Upvotes: 0

Anupam
Anupam

Reputation: 8016

Suppose your navigation input box is like this

<input id="nav" type="text"/>

Then use the same handler for this input element

$("#nav").keydown(function (e) {

                if (e.keyCode == 74) {
                    window.location = 'page1.html'; // Key = J
                }
                else if (e.keyCode == 75) {
                    window.location = 'page2.html'; // Key = k
                }
                else if (e.keyCode == 76) {
                    window.location = 'page3.html'; // Key = L
                }

            });

Upvotes: 4

Related Questions