0

Is it possible to focus on a specific HTML table row/cell with the help of Javascript? For instance, if this row is after the browser fold then the browser would scroll down to the row upon focus.

I have some JS code that searches an HTML table for a user's string input. I would then like for this code to focus on this word if it is found (Safari/Chrome browsers).

var targetTable = document.getElementById("accountTable");

for (var rowIndex = 1 + searchStart; rowIndex < targetTable.rows.length; rowIndex++)
{
    var rowData = '';
    rowData = targetTable.rows.item(rowIndex).cells.item(0).textContent;
    if (rowData.indexOf(str) != -1)
    {
                //focus on the row?
    }
}
101010110101
  • 1,940
  • 8
  • 31
  • 42
  • Focus? Form fields get focus. Table rows don't. Do mean highlighted in some way? – John Conde Mar 04 '13 at 16:48
  • Assuming it is a giant table, I basically want the browser to scroll down to the row. – 101010110101 Mar 04 '13 at 16:50
  • Ok. Do you use jquery or any library like that? – John Conde Mar 04 '13 at 16:52
  • 1
    If you don't care about an animation you can use scrollTo(x, y). If you want a nice animation and are using jquery you could use jQuery's scrollTo. If you want an animation and don't use jQuery you can refer to this thread: http://stackoverflow.com/questions/8917921/cross-browser-javascript-not-jquery-scroll-to-top-animation – Brandon Mar 04 '13 at 16:54

2 Answers2

2

You could give each row a HTML ID (either dynamically or statically depending on your needs) which matches the content and then use URI fragments to focus on it. You could basically use your current code and use

location.hash = rowData;

If the content matches the user input. This would of course be cumbersome if you've got whole sentences in the row you want to focus on, but for a simple table, it would work.

Kenneth
  • 416
  • 4
  • 13
1

I was able to achieve this by using scrollIntoView().

101010110101
  • 1,940
  • 8
  • 31
  • 42