satya
Fri Jan 12 2024
we can interact with browser events like click
on a element in rails using Stimulus
Make sure you have @hotwired/stimulus
installed .
Generate a stimulus controller by running the below commands.
./bin/rails generate stimulus controllerName
./bin/rails stimulus:manifest:update
Here , say my controllerName is tooltip
, this will create a controller called tooltip_controller.js
in app/javascripts/controllers
directory & also link the file in app/javascripts/controllers/index.js
.
For eg: my functionality is i want to toggle the tooltip visibility so the controller code will look like this
import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="tooltip"
export default class extends Controller {
connect() {}
toggleToolTip(event) {
event.preventDefault();
this.element.lastElementChild.classList.toggle("hidden");
}
}
And in your view file we need to wrap our parent div with an attribute called data-controller="tooltip"
so the code will look like this
<div class="relative" data-controller="tooltip">
<%= link_to "#", id: "avatar-link", data: { action: "click->tooltip#toggleToolTip" } do %>
<%= image_tag(your_image, alt: "Avatar", class: "...classnames") %>
<% end %>
<div class="..classnames hidden" id="tooltip-container">
... your tooltip contents
</div>
</div>
so here on click of the image it will toggle the tooltip container , if you take a close look on -> data: { action: "click->tooltip#toggleToolTip" }
this is simply saying perform the click
action on tooltip
controller using toggleToolTip
method defined above.