Files
openfoodnetwork/app/webpacker/controllers/floating_label_controller.js
Jean-Baptiste Bellet 93e736fdf6 Use label as a placeholder that move above the input when focused
Couldn't make a pure CSS version because of the way rails generates its errors (it add `<span />` over the element, either `input` or `label`, itself)
2022-12-27 10:47:18 +01:00

31 lines
788 B
JavaScript

import { Controller } from "stimulus";
export default class extends Controller {
connect() {
const input = this.element.querySelector("input");
input.addEventListener("focus", this.focus.bind(this));
input.addEventListener("blur", this.blur.bind(this));
if (input.value.length > 0) {
this.focus();
}
const label = this.element.querySelector("label");
// Add transition class to the label and display the label
// after a short delay to avoid flickering
setTimeout(() => {
label.classList.add("with-transition");
label.style.display = "block";
}, 100);
}
focus() {
this.element.classList.add("active");
}
blur(e) {
if (e.target.value.length === 0) {
this.element.classList.remove("active");
}
}
}