Skip to content

Blogging On Rails

Everything on Rails!

Convert your jQuery snippet to a Stimulus controller

Getting started with Stimulus can be as easy as converting a small jQuery snippet into a Stimulus controller. Here are three conventions that will make the conversion really quick. This assumes you’ve setup Stimulus already.

’turbolinks:load' to connect()

Any setup that the jQuery snippet does when the page is loaded can be moved to the connect() or initialize() functions. connect() usually makes sense for configuration that needs access to the page’s DOM. initialize() is best for work that is independent of the DOM, like initializing variables.

IDs to Targets

Any time an element is accessed in jQuery by its id, it becomes a perfect candidate for a stimulus target.

This code:

$('#book_title').attr("value", "Great Expectations")

can become:

static targets = ['bookTitle'];
// elsewhere in the controller
this.bookTitleTarget.setAttribute('value', 'Great Expectations')

This small example may not seem like an improvement, but consider more complicated situations. The target model handles front end complexity, and helps to keep the Javascript code neatly together as the web app scales.

jQuery Events to Controller Actions

Any event handlers added to elements now become actions on the controller.

$("#my_button").click(function() {
 	console.log("button clicked");
 });

using jQuery becomes

clicked( event ) {
  console.log("button clicked");
}

In the HTML, the data-action attribute needs to be added to the element that will send the click action to the clicked() method.

Leveling up

If you have an app with small amounts of jQuery, this would be a great time to look at one, and even on paper, sketch out the conversion to a Stimulus controller.

The Possibilities are endless

These three conventions can become the starting point for introducing Stimulus into a web app. Adding interactivity doesn’t need to mean rewriting everything from scratch in a new framework. With some straight forward Javascript refactoring, and a few tweaks to the HTML, web apps can become even better to the end user.

Comments or Questions? Let me know how your experience went below.

Want To Learn More?

Try out some more of my Stimulus.js Tutorials.

Make Interactivity Default 

Make your web app interactive now with easy to use and simple Stimulus.js controllers. 

Enter your email and get a free sample of my Stimulus Tutorials ebook.

We won’t send you spam. Unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2024 John Beatty. All rights reserved.