### Install Dependencies and Run Tests
Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md
Install project dependencies using Bundler and run the test suite.
```bash
bundle install
bundle exec rake test
```
--------------------------------
### Install Gem and Generate
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md
Install the gem using Bundler. The generator command may be available in older Rails versions.
```bash
bundle install
rails generate jquery:install # If available in older Rails versions
```
--------------------------------
### Rails Engine Integration Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md
Example demonstrating the automatic loading of Jquery::Rails::Engine for Rails integration.
```ruby
require 'jquery-rails'
# Jquery::Rails::Engine is automatically loaded
```
--------------------------------
### Asset Pipeline Setup (application.js)
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md
Configure your application.js to include jQuery and related files using Sprockets directives.
```javascript
//= require jquery3
//= require jquery_ujs
//= require_self
//= require_tree .
$(function() {
console.log('jQuery is ready!');
console.log('jQuery version:', $.fn.jquery);
});
```
--------------------------------
### Complete Form Example with Data Attributes
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md
This example demonstrates a complete HTML form utilizing various data attributes for remote submission, JSON data type, confirmation messages, and dynamic button text. It also includes JavaScript event handlers for AJAX responses.
```html
```
--------------------------------
### Target as Argument (appendTo/prependTo) Assertion Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Tests jQuery methods where the target selector is passed as an argument, such as appendTo and prependTo. This example shows how to assert these operations and verify the appended/prepended content.
```javascript
// Response:
// $("
Product
").appendTo("#inventory");
// $("
New
").prependTo("#items");
```
```ruby
assert_select_jquery :appendTo, '#inventory' do
assert_select '.item', 'Product'
end
assert_select_jquery :prependTo, '#items' do
assert_select '.header', 'New'
end
```
--------------------------------
### Rails Unit Test Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Demonstrates including the necessary module to use assert_select_jquery in a Rails unit test class.
```ruby
class MyUnitTest < ActiveSupport::TestCase
include Rails::Dom::Testing::Assertions::SelectorAssertions
# assert_select_jquery available here too
end
```
--------------------------------
### Event Handling for User Confirmation
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Provides examples of how to hook into the 'confirm' and 'confirm:complete' events to customize or prevent confirmation dialogs and log actions.
```javascript
$('a.delete').on('confirm', function(e) {
var sure = validateBeforeDelete();
if (!sure) {
e.preventDefault(); // Prevent confirmation dialog
}
});
$('a.delete').on('confirm:complete', function(e, answer) {
if (answer) {
logDeletion();
}
});
```
--------------------------------
### Development Asset Serving
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
In development, uncompressed JavaScript assets like jQuery are served directly. This example shows including jQuery 3 in `application.js`.
```javascript
// app/assets/javascripts/application.js
//= require jquery3
```
--------------------------------
### Rails Integration Test Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Shows how to use assert_select_jquery within a Rails integration test class.
```ruby
class MyControllerTest < ActionDispatch::IntegrationTest
# assert_select_jquery available here
end
```
--------------------------------
### Nested Assertions on HTML Structure Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Demonstrates deeply nested assertions within a block to verify complex HTML structures generated by jQuery. This example shows how to assert elements within elements, including attribute selectors.
```javascript
// Response:
// $("#modal").html("
Edit User
");
```
```ruby
assert_select_jquery :html, '#modal' do
assert_select '.header'
assert_select 'h1', 'Edit User'
assert_select 'form' do
assert_select 'input[name=username]'
end
end
```
--------------------------------
### Example Usage of Blank Inputs
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Demonstrates how to use the blankInputs function to check for missing input values in a form and access the count of blank inputs.
```javascript
var missing = $.rails.blankInputs($('form'));
if (missing) {
// missing.length inputs are empty
}
```
--------------------------------
### Example Test Case with Selector Assertions
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/MODULE_STRUCTURE.md
Demonstrates how to use `assert_select_jquery` within a test case by including `Rails::Dom::Testing::Assertions::SelectorAssertions`.
```ruby
class MyTest < ActiveSupport::TestCase
include Rails::Dom::Testing::Assertions::SelectorAssertions
def test_something
assert_select_jquery :show, '#notice'
end
end
```
--------------------------------
### Basic Method Assertion Examples
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Demonstrates basic assertions for jQuery method calls, including calls with and without specific selectors. Shows passing and failing cases.
```javascript
// Response:
// $("#message").show();
// $("#notice").hide();
```
```ruby
assert_select_jquery :show
# ✓ Passes — finds $("#message").show()
assert_select_jquery :show, '#message'
# ✓ Passes — finds $("#message").show()
assert_select_jquery :hide, '#notice'
# ✓ Passes — finds $("#notice").hide()
assert_select_jquery :remove, '#notice'
# ✗ Fails — no remove() call found
```
--------------------------------
### Animation Method with Option Assertion Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Asserts jQuery animation methods with specific options and selectors. This example demonstrates testing calls like .show('slide', 300) and verifies the correct option is used.
```javascript
// Response:
// $("#sidebar").show('slide', 300);
// $("#sidebar").hide('fade', 500);
```
```ruby
assert_select_jquery :show, :slide, '#sidebar'
# ✓ Passes
assert_select_jquery :hide, :fade, '#sidebar'
# ✓ Passes
assert_select_jquery :hide, :blind, '#sidebar'
# ✗ Fails — 'blind' option not found
```
--------------------------------
### HTML Manipulation with Block Assertion Example
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/assert_select_jquery.md
Tests HTML manipulation using the :html method and verifies the resulting DOM structure with nested assertions. This example shows how to check for specific elements and text content within the manipulated HTML.
```javascript
// Response:
// $("#user-list").html("
Alice
");
```
```ruby
assert_select_jquery :html, '#user-list' do
assert_select '.user'
assert_select '.name', 'Alice'
end
```
--------------------------------
### Custom AJAX Implementation
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Replace the default AJAX implementation with a custom one using `$.rails.ajax`. This example uses the Fetch API.
```javascript
$.rails.ajax = function(options) {
return fetch(options.url, {
method: options.type,
body: options.data
}).then(r => r.json());
};
```
--------------------------------
### Example Rails Application Integration
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/Rails-Engine.md
Demonstrates how to add the jquery-rails gem to the Gemfile and include jQuery and jQuery-UJS in the application's JavaScript manifest, along with a basic jQuery ready function.
```ruby
# Gemfile
gem 'jquery-rails'
# config/assets/javascripts/application.js
//= require jquery3
//= require jquery_ujs
//= require_tree .
// Now jQuery and Rails UJS are available globally
$(function() {
// jQuery is ready
$('a[data-confirm]').on('click', function() {
// Rails UJS handles confirmation dialogs
});
});
```
--------------------------------
### Example of Stopping Event Propagation
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Shows how to prevent the default form submission behavior and stop event propagation using the stopEverything function.
```javascript
$('form').on('submit', function(e) {
e.preventDefault();
$.rails.stopEverything(e);
});
```
--------------------------------
### Importmap Configuration for jQuery
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
Configure Importmap to pin jQuery from a CDN. This example pins jQuery version 3.7.1 and also pins 'rails.js' with preloading enabled.
```javascript
// config/importmap.rb
pin "jquery", to: "https://code.jquery.com/jquery-3.7.1.min.js"
pin "rails", to: "rails.js", preload: true
```
--------------------------------
### ajax(options)
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Wrapper around jQuery's $.ajax() that can be customized. It allows for replacing the default AJAX implementation with a custom one, for example, using the Fetch API.
```APIDOC
## ajax(options)
### Description
Wrapper around `$.ajax()` that can be customized. Enables replacing the default AJAX implementation.
### Parameters
#### Options
- **options** (Object) - jQuery AJAX options
### Returns
jqXHR
### Example
```javascript
$.rails.ajax = function(options) {
return fetch(options.url, {
method: options.type,
body: options.data
}).then(r => r.json());
};
```
```
--------------------------------
### Add jquery-rails Gem to Gemfile
Source: https://github.com/rails/jquery-rails/blob/master/README.md
To install the jquery-rails gem, add the specified line to your application's Gemfile.
```ruby
gem 'jquery-rails'
```
--------------------------------
### Custom Confirmation Dialog
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Implement a custom modal dialog for confirmations instead of the browser's default `confirm()` function. This example uses a Promise to handle the asynchronous nature of modal interactions.
```javascript
// Use custom modal instead of browser confirm
$.rails.confirm = function(message) {
return new Promise(resolve => {
showCustomModal(message, resolve);
});
};
```
--------------------------------
### Correct jQuery-UJS Dependency Order
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
Ensure jQuery is loaded before jQuery-UJS in the asset manifest to prevent errors. This example shows the correct order.
```javascript
// Correct order
//= require jquery3
//= require jquery_ujs
// Wrong order (will fail)
//= require jquery_ujs
//= require jquery3
```
--------------------------------
### Source Map Usage in Production
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
Source maps are automatically served by browsers when present, allowing debugging of minified code in production. This example shows the HTML for a minified jQuery script.
```html
```
--------------------------------
### Automatic Initialization Check
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Demonstrates the condition under which jQuery-UJS automatically initializes itself. The `rails:attachBindings` event is fired to trigger setup, including CSRF protection and event binding.
```javascript
if (rails.fire($document, 'rails:attachBindings')) {
// Automatic setup:
// 1. Adds CSRF protection to all AJAX requests
// 2. Binds click/change/submit handlers to selector matches
// 3. Sets up event delegation
}
```
--------------------------------
### Production Asset Compilation
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
During `rails assets:precompile`, assets are minified, fingerprinted, and gzipped for production. This example shows the resulting script tag for jQuery 3.
```html
```
--------------------------------
### Custom Application JavaScript with jQuery
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
Add custom JavaScript code after asset manifest requires. This example shows initializing code within a jQuery ready function.
```javascript
// app/assets/javascripts/application.js
//= require jquery3
//= require jquery_ujs
$(function() {
// Your code here
console.log('jQuery is ready');
});
// Or in a separate file
//= require_tree .
```
--------------------------------
### Listening to AJAX BeforeSend Event
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md
JavaScript code to listen for the `ajax:beforeSend` event, which fires before an AJAX request is sent. This example logs the request URL to the console.
```javascript
$(document).on('ajax:beforeSend', function(e, xhr, settings) {
console.log('Starting AJAX request to:', settings.url);
});
```
--------------------------------
### Test ERB with jQuery for View Rendering
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/TESTING_GUIDE.md
Example of testing JavaScript generated by ERB templates, specifically how to assert HTML updates and element visibility using jQuery.
```erb
# app/views/users/create.js.erb
$("#user-form").html("<%= escape_javascript(render 'form') %>");
$("#success-message").show("blind");
```
```ruby
# test/integration/user_creation_test.rb
def test_create_user
post users_path, params: { user: { name: 'John' } }, xhr: true
assert_select_jquery :html, '#user-form' do
assert_select 'form'
end
assert_select_jquery :show, :blind, '#success-message'
end
```
--------------------------------
### Remote Form with Dynamic Data Loading
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md
This example shows a form that uses data attributes to make a remote AJAX request when a customer is selected. The response updates a customer details section. Ensure the controller has a `customer_details` action that renders JSON.
```erb
```
--------------------------------
### Rails Controller for Customer Details
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md
This controller action handles requests for customer details, finding the customer by ID and rendering their information as JSON. This is used by the remote form example.
```ruby
# app/controllers/orders_controller.rb
class OrdersController < ApplicationController
def customer_details
@customer = Customer.find(params[:id])
render json: @customer
end
end
```
--------------------------------
### Listening to AJAX Success Event
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md
JavaScript code to listen for the `ajax:success` event, which fires upon a successful AJAX response. This example logs a success message to the console.
```javascript
$(document).on('ajax:success', function(e, data, status, xhr) {
console.log('Request succeeded');
});
```
--------------------------------
### Link with Multiple Data Attributes
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/DATA_ATTRIBUTES.md
Use data attributes on links to control method, confirmation, AJAX requests, and button text during submission. This example demonstrates a delete link with confirmation and AJAX submission.
```html
Delete
```
--------------------------------
### Accessing Version Constants in Ruby
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/VERSIONS.md
Demonstrates how to require the version file and access all defined version constants within a Ruby environment.
```ruby
require 'jquery/rails/version'
Jquery::Rails::VERSION # "4.6.1"
Jquery::Rails::JQUERY_VERSION # "1.12.4"
Jquery::Rails::JQUERY_2_VERSION # "2.2.4"
Jquery::Rails::JQUERY_3_VERSION # "3.7.1"
Jquery::Rails::JQUERY_UJS_VERSION # "1.2.3"
```
--------------------------------
### List All Available Assets
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/ASSET_INCLUSION.md
Use the `rails assets:precompile --trace` command to list all assets that are being precompiled. This is useful for debugging the asset pipeline.
```bash
# List all available assets
rails assets:precompile --trace
```
--------------------------------
### Stage and Commit Changes
Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md
Stage all changes and create a commit with a descriptive log message.
```bash
git add ...
git commit
```
--------------------------------
### Fork and Clone Project
Source: https://github.com/rails/jquery-rails/blob/master/CONTRIBUTING.md
Clone the forked project and set up the upstream remote for future updates.
```bash
git clone https://github.com/contributor/jquery-rails.git
cd jquery-rails
git remote add upstream https://github.com/rails/jquery-rails.git
```
--------------------------------
### href(element)
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Gets an element's href attribute. This method is overridable for custom link handling.
```APIDOC
## href(element)
### Description
Gets an element's href attribute. Overridable for custom link handling.
### Parameters
#### Element
- **element** (jQuery) - Link element
### Returns
String - The element's href attribute
### Example
```javascript
var url = $.rails.href($('a.api-link'));
```
```
--------------------------------
### Get Element Href
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/api-reference/jQuery-UJS-API.md
Retrieve the href attribute of a link element. This function can be overridden for custom link handling.
```javascript
var url = $.rails.href($('a.api-link'));
```
--------------------------------
### Asset Pipeline Manifest Format
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/USAGE_EXAMPLES.md
An alternative way to declare asset dependencies using the manifest format.
```javascript
/*
*= require jquery3
*= require jquery_ujs
*= require_self
*= require_tree .
*/
```
--------------------------------
### HTML Data Attributes for Unobtrusive JavaScript
Source: https://github.com/rails/jquery-rails/blob/master/_autodocs/README.md
Examples of HTML data attributes used by jQuery-UJS for unobtrusive JavaScript interactions.
```html