Last active
February 14, 2025 17:43
-
-
Save glaucocustodio/e79edf3114057f2d506b24cbc0abb2d1 to your computer and use it in GitHub Desktop.
a Stimulus controller to disable elements on click since Rails 7.0 has dropped UJS (so `data-disable-with` is no longer available)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from '@hotwired/stimulus' | |
/* | |
Disable a button when it is clicked | |
Ps: Rails 7.0 has dropped UJS, so `data-disable-with` is no longer available | |
Example usage: | |
= button_to 'Confirm', foo_path, method: :post, class: "btn btn-warning", data: {controller: 'disable-with', 'disable-with-content-value' => 'Confirming...'} | |
*/ | |
export default class extends Controller { | |
static values = { content: String } | |
connect() { | |
const clickableElement = this.element | |
clickableElement.addEventListener('click', () => { | |
const isAnchor = clickableElement.tagName === 'A' | |
if (isAnchor) { | |
clickableElement.innerHTML = this.contentValue | |
} else { | |
clickableElement.value = this.contentValue | |
} | |
// setTimeout allow the event to fully propagate through any other event listeners or | |
// parent elements before disabling the clickableElement | |
setTimeout(() => { | |
if (isAnchor) { | |
clickableElement.classList.add('disabled') | |
} else { | |
clickableElement.disabled = true | |
} | |
}, 0) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment