Eric Parshall

July 13, 2021

Trying to use Turbo.visit, but within a Turbo Frame

For reasons, I needed to be able to programmatically navigate within a Turbo Frame. I was hoping that Turbo.visit(path) would work, but it always affected the entire page. I found a feature that is only lightly documented. If I can select the turbo-frame element I can set the "src" attribute to make it load a new path. Here is a Stimulus controller I made to make table rows clickable. It will work within a Turbo Frame or just a regular table on a page:


import { Controller } from "stimulus"

export default class extends Controller {
  goToRecord(event) {
    // Hyperlink clicks automatically work within the Turbo Frame
    if (event.target.tagName === "A") {
      return;
    }

    let row = event.currentTarget;
    let path = row.dataset.href;
    let target = row.dataset.target;

    if (path) {
      if (target === "frame") {
        row.closest("turbo-frame").src = path;
      } else {
        Turbo.visit(path, { action: "replace" });
      }
    }
  }
}

---
Thanks,
Eric