Hi All,
I am using jquery in one of my projects. I have a scenario where I have to add keyboard events to the td cells of a table to move up and down in them. I was able to achieve this using the following code.
- <script type="text/javascript">
- var tds = jQuery("#myTable td");
- tds.bind('keyup', function(event){
- var key = event.which;
- moveSelection(key, jQuery(this), tds);
- event.preventDefault();
- });
- function moveSelection(key, current_td, all_tds){
- var index = parseInt(current_td.attr("id"));
- if (key == 13) {
- current_td.click();
- } else if(key == 38) {
- if(all_tds[index - 1]){
- all_tds[index - 1].focus();
- }
- } else if(key == 40) {
- if(index < all_tds.length){
- var next_index = index + 1;
- if(next_index < all_tds.length){
- all_tds[index + 1].focus();
- }
- }
- }
- }
- </script>
- 13=Enter, 38=PageUp, 40=PageDown.
This is how my table look like. This is an ajax response:
- <table style="position:absolute;" id="myTable">
- <tr>
- <td tabindex="0" id="0">Users</td>
- <td tabindex="0" id="1">Cities</td>
- <td tabindex="0" id="2">Pages</td>
- <td tabindex="0" id="3">Links</td>
- <td tabindex="0" id="4">Guidelines</td>
- <td tabindex="0" id="5">FAQs</td>
- <td tabindex="0" id="6">Help</td>
- </tr>
- </table>
I was able to move through the td cells if the page has no scroll bars. But when the page has scroll bars, when I use PageUp/PageDown keys two things happen.
1. My page scrolls up/down based on the key pressed.()
2. The respective td selection moves/up based on the key pressed.
In the first case, it might be because of the events are bound to the page as well as my table tds. How ca I prevent this. I dont want my page to scroll when I am dealing with my table. I tried a lot but failed. Looking here for some help.
Please find the screenshot in the attachment.