0
# Rails UJS
1
2
Rails UJS (`@rails/ujs`) is a JavaScript library that provides unobtrusive scripting support for Ruby on Rails applications. It enables modern JavaScript behaviors without requiring inline event handlers by using HTML5 data attributes. The library works independently of any JavaScript framework and provides comprehensive support for AJAX requests, form handling, CSRF protection, and UI element state management.
3
4
## Package Information
5
6
- **Package Name**: @rails/ujs
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install @rails/ujs --save`
10
11
## Core Imports
12
13
```javascript
14
import Rails from "@rails/ujs";
15
Rails.start();
16
```
17
18
For CommonJS:
19
20
```javascript
21
const Rails = require("@rails/ujs");
22
Rails.start();
23
```
24
25
Asset Pipeline (Sprockets):
26
27
```javascript
28
//= require rails-ujs
29
```
30
31
## Basic Usage
32
33
```javascript
34
import Rails from "@rails/ujs";
35
36
// Initialize the library (required for ES modules)
37
Rails.start();
38
39
// The library automatically binds to elements with data attributes:
40
// <a href="/posts/1" data-method="delete" data-confirm="Are you sure?">Delete</a>
41
// <form data-remote="true" data-confirm="Submit form?">...</form>
42
// <input type="submit" data-disable-with="Processing..." />
43
```
44
45
## Architecture
46
47
Rails UJS is organized around several key components:
48
49
- **Event Delegation System**: Uses a single event delegation approach for performance and dynamic content support
50
- **Data Attribute Processing**: Converts HTML5 data attributes into JavaScript behaviors
51
- **Modular Design**: Organized into utilities (DOM, AJAX, CSRF) and features (confirm, disable, method, remote)
52
- **Framework Independence**: Works without jQuery or other frameworks, with optional jQuery integration
53
- **CSRF Protection**: Automatic Cross-Site Request Forgery token management for all AJAX requests
54
55
## Capabilities
56
57
### AJAX and Remote Requests
58
59
Core AJAX functionality for making HTTP requests with Rails conventions, including automatic CSRF protection, response processing, and cross-domain detection.
60
61
```javascript { .api }
62
function ajax(options: AjaxOptions): boolean | XMLHttpRequest;
63
64
interface AjaxOptions {
65
url?: string;
66
type?: string;
67
data?: string | FormData;
68
dataType?: string;
69
beforeSend?: (xhr: XMLHttpRequest, options: AjaxOptions) => boolean;
70
success?: (response: any, statusText: string, xhr: XMLHttpRequest) => void;
71
error?: (response: any, statusText: string, xhr: XMLHttpRequest) => void;
72
complete?: (xhr: XMLHttpRequest, statusText: string) => void;
73
crossDomain?: boolean;
74
withCredentials?: boolean;
75
}
76
```
77
78
[AJAX and Remote Requests](./ajax-remote.md)
79
80
### CSRF Protection
81
82
Cross-Site Request Forgery protection system that automatically handles CSRF tokens for all requests and forms, including Content Security Policy nonce support for secure script execution.
83
84
```javascript { .api }
85
function csrfToken(): string | null;
86
function csrfParam(): string | null;
87
function CSRFProtection(xhr: XMLHttpRequest): void;
88
function refreshCSRFTokens(): void;
89
function cspNonce(): string | null;
90
function loadCSPNonce(): string | null;
91
```
92
93
[CSRF Protection](./csrf-protection.md)
94
95
### Element State Management
96
97
System for enabling and disabling form elements and links during processing, including visual feedback management.
98
99
```javascript { .api }
100
function enableElement(element: Element | Event): void;
101
function disableElement(element: Element | Event): void;
102
function handleDisabledElement(event: Event): void;
103
```
104
105
[Element State Management](./element-state.md)
106
107
### DOM Utilities
108
109
Core DOM manipulation and querying utilities used throughout the library.
110
111
```javascript { .api }
112
function $(selector: string): Element[];
113
function matches(element: Element, selector: string | SelectorObject): boolean;
114
function getData(element: Element, key: string): any;
115
function setData(element: Element, key: string, value: any): any;
116
function isContentEditable(element: Element): boolean;
117
```
118
119
[DOM Utilities](./dom-utilities.md)
120
121
### Event System
122
123
Custom event system and delegation utilities for managing user interactions and library events.
124
125
```javascript { .api }
126
function fire(obj: EventTarget, name: string, data?: any): boolean;
127
function delegate(element: Element, selector: string, eventType: string, handler: Function): void;
128
function stopEverything(event: Event): void;
129
```
130
131
[Event System](./event-system.md)
132
133
### Form Handling
134
135
Form serialization and element management utilities for handling form submissions and form state.
136
137
```javascript { .api }
138
function serializeElement(element: Element, additionalParam?: {name: string, value: string}): string;
139
function formElements(form: Element, selector: string): Element[];
140
function formSubmitButtonClick(event: Event): void;
141
```
142
143
[Form Handling](./form-handling.md)
144
145
### Feature Handlers
146
147
High-level handlers that implement the core Rails UJS behaviors for method overrides, remote requests, confirmations, and element disabling.
148
149
```javascript { .api }
150
function handleConfirm(event: Event): void;
151
function handleMethod(event: Event): void;
152
function handleRemote(event: Event): void;
153
function preventInsignificantClick(event: Event): void;
154
```
155
156
[Feature Handlers](./feature-handlers.md)
157
158
### Initialization
159
160
Core initialization functionality required to activate Rails UJS event delegation and data attribute processing.
161
162
```javascript { .api }
163
/**
164
* Initialize Rails UJS and set up all event delegation
165
* @returns true if successfully initialized
166
* @throws Error if Rails UJS has already been loaded
167
*/
168
function start(): boolean;
169
```
170
171
### Selector Constants
172
173
CSS selectors used internally by Rails UJS for element targeting and event delegation.
174
175
```javascript { .api }
176
const linkClickSelector: string;
177
const buttonClickSelector: SelectorObject;
178
const inputChangeSelector: string;
179
const formSubmitSelector: string;
180
const formInputClickSelector: string;
181
const formDisableSelector: string;
182
const formEnableSelector: string;
183
const fileInputSelector: string;
184
const linkDisableSelector: string;
185
const buttonDisableSelector: string;
186
```
187
188
## Global Types
189
190
```javascript { .api }
191
interface SelectorObject {
192
selector: string;
193
exclude: string;
194
}
195
196
interface RailsObject {
197
$: (selector: string) => Element[];
198
ajax: (options: AjaxOptions) => boolean | XMLHttpRequest;
199
confirm: (message: string, element: Element) => boolean;
200
href: (element: Element) => string;
201
start: () => boolean;
202
[key: string]: any;
203
}
204
```