Event listener (on click, link to show page) only working once in Ruby on Rails project

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.

        <% @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 %>
        <% end %>

  document.addEventListener("DOMContentLoaded", () => {
      const rows = document.querySelectorAll("tr[data-href]");

      rows.forEach(row => {
          row.addEventListener("click", () => {
              window.location.href = row.dataset.href;

23 thoughts on “Event listener (on click, link to show page) only working once in Ruby on Rails project”

  1. 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 with Turbolinks.visit(row.dataset.href)

    The Turbolinks docs have more info on this.


Leave a Comment