Noob here. I have an index.html.erb
file that lists clients from my database in a table format and each row within the table is clickable as a link to each client’s respective show page. The only problem is that although my attached event listener works, it is only working once. If I navigate back to my index page, I cannot click on the client index table rows anymore. I followed a YouTube tutorial to get this far. I trimmed my code down to what I think is relevant. Thank you in advance!
EDIT: I want to emphasize that this is within an HTML table, talking about clicking on HTML table rows. This means ordinary <a>
tags and ERB link_to
are not options.
<tbody>
<% @clients.each do |client| %>
<tr data-href="<%= client_path(client) %>" class="odd:bg-white even:bg-gray-100 cursor-pointer hover:bg-indigo-300 hover:ring-blue-700 hover:ring-inset">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
<%= client.first_name + " " + client.last_name %>
</td>
</tr>
<% end %>
</tbody>
<script>
document.addEventListener("DOMContentLoaded", () => {
const rows = document.querySelectorAll("tr[data-href]");
rows.forEach(row => {
row.addEventListener("click", () => {
window.location.href = row.dataset.href;
});
});
});
</script>
I’m guessing it’s a conflict with Turbolinks which is enabled on new Rails projects by default (for now). Try replacing
window.location.href = row.dataset.href
withTurbolinks.visit(row.dataset.href)
The Turbolinks docs have more info on this.