Sander S
Sander S

Reputation: 3

Jump to table row and Highlight it in html?

I got a long table and different entries are related to each other, so I link them to like this:

<tr>
    <th>Thing </th>
    <th>related to Thing </th>
</tr>
<tr>
    <td><a name = "t1"/>Thing 1</td>
    <td><a href = "#t2">Thing2 is related </a></td>
</tr>
<tr>
    <td><a name = "t2"/>Thing2</td>
    <td><a href = "#t1">Thing1 is related </a></td>
</tr>

Now, I want that when I click on "Thing2 is related" I jump down the page (Which works), but then I would like this row to light up shortly to point out Which line is meant. Is there something to do this?

Upvotes: 0

Views: 1810

Answers (2)

Oliver Tušla
Oliver Tušla

Reputation: 148

You need a onclick function so that when the Related hyperlink is clicked it knows what to highlight.

function highlight(selector) {
  var highlighted = document.querySelector("a[name=" + selector + "]");
  var originalColor = highlighted.style.backgroundColor;
  highlighted.style.backgroundColor = "yellow";
  setTimeout(function() {
    highlighted.style.backgroundColor = originalColor;
  }, 1000);
}

function setHighlightCall(selector) {
  return function() {
    highlight(selector);
  };
}

window.onload = function() {
  var anchors = document.querySelectorAll("a[href^='#']");
  anchors.forEach(function(anchor) {
    var anchorName = anchor.href.match(/#([^#]+)$/)[1];
    anchor.onclick = setHighlightCall(anchorName);
  });
};
<tr>
  <td><a name="t1"/>Thing 1</td>
  <td><a href="#t2">Thing2 is related </a></td>
</tr>
<div style="height:500px"></div>
<tr>
  <td><a name="t2"/>Thing2</td>
  <td><a href="#t1">Thing1 is related </a></td>
</tr>

Upvotes: 0

msg
msg

Reputation: 8181

If a bit of jQuery is acceptable, then yes. You will have to do one minor change to your html, changing name attribute to an id.

// Listen for clicks on '.link' elements
$('table').on('click', '.link', function() {
  // Find previously selected items and remove the class, restricting the search to the table.
  $('.related', 'table').removeClass('related')
  // Find the click target
  target = $(this).attr('href');
  // Find its 'tr' and highlight it
  $(target).closest('tr').addClass('related')
});
.related {
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Thing </th>
    <th>related to Thing </th>
  </tr>
  <tr>
    <td><a id="t1" />Thing 1</td>
    <td><a class="link" href="#t2">Thing2 is related </a></td>
  </tr>
  <tr>
    <td><a id="t2" />Thing2</td>
    <td><a class="link" href="#t1">Thing1 is related </a></td>
  </tr>
</table>

Upvotes: 1

Related Questions