Clickable div with Hotwire / Turbo Frames

I’m trying to make a clickable div, so when you click on the text, it loads a frame to edit the value.

The only way I could get it to work was to keep the edit link in place, make it a target and hide it. Then in my stimulus controller call the click event on the target.

What I had wanted to do was just pass the edit url to the controller and then trigger the frame action with “Turbo.visit(this.urlValue, { action: “replace” })” but that doesn’t seem to work.

Does anyone know a cleaner way to do this without a hidden link?

Thanks!

View:

<%= turbo_frame_tag dom_id(tweet) do %>
  <div class="card card-body" data-controller="tweet" >
    <div data-action="click->tweet#edit_tweet" data-tweet-url-value="<%= edit_tweet_path(tweet.id) %>"><%= tweet.body %></div>

    <div class="mt-2">
      <%= link_to "Likes (#{tweet.likes_count})", like_a_tweet_path(tweet.id) %>
      <%= button_to "Retweets (#{tweet.retweets_count})", tweet_retweet_path(tweet), method: :post %>

      <%= link_to "Edit", edit_tweet_path(tweet), :data => { "tweet-target" => 'editlink' }, :style => "display:none;" %>
    </div>
  </div>
<% end %>

Tweet Stimulus Controller:
import { Turbo } from "@hotwired/turbo-rails"
import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "editlink" ]
  static values = {
    url: String
  }

  edit_tweet() {
    //Turbo.visit(this.urlValue, { action: "replace" })
    this.editlinkTarget.click();
  }
}
1 Like

Why not just make the text inside the div a link? I believe the HTML5 standard even allows you to put divs inside anchor tags, so you could include the entire card.

If that’s not an option, we could also look in the Turbo source to see what event the turbo-frames listen for. Then you could just dispatch that event instead of having to click a hidden link.

I’m unable to source-dive right now, but I bet just using a normal link would work fine.

Thanks, yes in this case I could just use anchor tag and just confirmed that works.

I’ll dive into the turbo source to see if there is way to trigger the event from javascript because I still have use cases for that.

1 Like