Fire a Stimulus Controller Action on a Click Event

Ian Jones
InstructorIan Jones

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

In our Stimulus App, we change the connect method to a greet action (this method name can be anything.

We then wire that action up to our HTML button by adding data-action to it and passing the function that we want to fire, in this case, its click->example#greet.

Instructor: [0:00] Here, we have a stimulus controller named example_controller. In our html, we're wiring up our controller to this div. Instead of firing console.log('Hello') on connect, we're going to change this to an action called greet.

[0:20] The next thing we need to do is jump over to our html. We need to add a button. We'll give it a text of Greet. To wire up our greet action from our controller, we will add data-action="click." This is the DOM event that we're using.

[0:53] We tell stimulus to fire our greet method in our example_controller. When we refresh, and we open up our developer tools, hop over to the console. When we click Greet, we'll get Hello.

[1:09] To wrap up, all we did was create a method called greet on our controller class. We added a button to our html with an attribute of data-action and a value of click, which is the DOM event we want to fire our action on. Our action is our example_controller's greet method.