1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Connect a Stimulus Controller to your html

    Ian JonesIan Jones
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    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.