⚠️ This lesson is retired and might contain outdated information.

Connect a Stimulus Controller to your html

Ian Jones
InstructorIan Jones
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

The first thing you need to do is add the data-controller attribute the to html that you want to connect to Stimulus.

We added data-controller="example" so Stimulus expects an example_controller.js file to exist.

In our ExampleController class, we are going to use the connect method to show that we've connected our controller to the dom.

Instructor: [0:00] Here we have an HTML file that has a heading of Hello. To connect this heading to a stimulus controller, we need to add data-controller as an attribute to this element.

[0:20] Our controller is going to be named example. Let's head on over to our example_controller file. The first thing we need to do is import controller from stimulus. We need to export a class that extends controller. The controller class has a connect method that fires anytime a stimulus controller is connected to the DOM.

[1:13] Here, we'll console.log("Hello"). When we go over to our browser and pop open the DevTools, if we reload, we'll see that we got Hello from example_controller.

[1:34] To wrap up, the first thing you need to do to connect stimulus to your HTML is add the data-controller attribute. Next, you need to create a controller with the same name as the value of that attribute.

[1:51] Finally, we added a connect method to fire whenever stimulus connected to our HTML.

egghead
egghead
~ 7 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today