What is stimulus?
Stimulus is a JavaScript framework that enhances the behavior of HTML elements by connecting them to JavaScript controllers. It is designed to work with the HTML you already have, making it easy to add interactivity to your web applications without the need for a complex setup.
What are stimulus's main functionalities?
Controller Initialization
This feature allows you to initialize a Stimulus controller and connect it to HTML elements. The controller listens for events (like a button click) and executes the corresponding JavaScript function.
```html
<!-- HTML -->
<div data-controller="example">
<button data-action="click->example#sayHello">Click me</button>
</div>
<!-- JavaScript -->
import { Controller } from "stimulus";
export default class extends Controller {
sayHello() {
alert("Hello, Stimulus!");
}
}
```
Data Attributes
Stimulus uses data attributes to pass information from HTML to JavaScript. This example demonstrates how to use data attributes to store and retrieve data within a controller.
```html
<!-- HTML -->
<div data-controller="example" data-example-name="Stimulus">
<button data-action="click->example#greet">Greet</button>
</div>
<!-- JavaScript -->
import { Controller } from "stimulus";
export default class extends Controller {
greet() {
const name = this.data.get("name");
alert(`Hello, ${name}!`);
}
}
```
Targets
Targets in Stimulus allow you to easily reference specific elements within your controller. This example shows how to use targets to get the value of an input field and use it in a function.
```html
<!-- HTML -->
<div data-controller="example">
<input data-example-target="name" type="text" placeholder="Enter your name">
<button data-action="click->example#greet">Greet</button>
</div>
<!-- JavaScript -->
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["name"];
greet() {
const name = this.nameTarget.value;
alert(`Hello, ${name}!`);
}
}
```
Other packages similar to stimulus
alpinejs
Alpine.js is a lightweight JavaScript framework that offers similar functionality to Stimulus. It allows you to add interactivity to your HTML with minimal JavaScript. Compared to Stimulus, Alpine.js is more declarative and often requires less boilerplate code.
htmx
HTMX is a library that allows you to access modern browser features directly from HTML, making it easy to add AJAX, CSS Transitions, WebSockets, and Server-Sent Events to your web applications. While Stimulus focuses on connecting JavaScript controllers to HTML, HTMX focuses on enhancing HTML with modern web capabilities.
vue
Vue.js is a progressive JavaScript framework for building user interfaces. While it is more feature-rich and complex compared to Stimulus, it offers a similar approach to enhancing HTML with reactive data binding and component-based architecture.