Created
May 21, 2026 18:49
-
-
Save devhammed/1457dcc2fc7abc80475c441c92d6306b to your computer and use it in GitHub Desktop.
Alpine.js Floating Input Placeholder
This file contains hidden or 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
| window.Alpine.directive('placeholder', (el, context, framework) => { | |
| if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA') { | |
| throw new Error('The `x-placeholder` directive can only be used on an `input` or `textarea` element.'); | |
| } | |
| const placeholder = el.getAttribute('placeholder'); | |
| if (!placeholder) { | |
| return; | |
| } | |
| const pseudoPlaceholder = document.createElement('label'); | |
| pseudoPlaceholder.htmlFor = el.id; | |
| pseudoPlaceholder.textContent = placeholder; | |
| pseudoPlaceholder.className = 'pseudo-placeholder'; | |
| el.after(pseudoPlaceholder); | |
| let pseudoPlaceholderStyles = document.getElementById('pseudo-placeholder-styles'); | |
| if (!pseudoPlaceholderStyles) { | |
| pseudoPlaceholderStyles = document.createElement('style'); | |
| pseudoPlaceholderStyles.id = 'pseudo-placeholder-styles'; | |
| pseudoPlaceholderStyles.textContent = ` | |
| .pseudo-placeholder { | |
| max-width: 95% !important; | |
| text-overflow: clip !important; | |
| font-size: 18px !important; | |
| position: absolute !important; | |
| top: 15px !important; | |
| left: 13px !important; | |
| right: 13px !important; | |
| color: gray !important; | |
| transition: top .25s, opacity .25s, font-size .25s !important; | |
| cursor: text !important; | |
| opacity: 0.1 !important; | |
| } | |
| *:has(> [x-placeholder]) { | |
| position: relative !important; | |
| } | |
| [x-placeholder]:focus + .pseudo-placeholder, | |
| [x-placeholder]:not(:placeholder-shown) + .pseudo-placeholder { | |
| top: 1px !important; | |
| font-size: 12px !important; | |
| opacity: 1 !important; | |
| } | |
| `; | |
| document.head.appendChild(pseudoPlaceholderStyles); | |
| } | |
| framework.cleanup(() => { | |
| pseudoPlaceholder.remove(); | |
| if (!document.querySelector('[x-placeholder]')) { | |
| pseudoPlaceholderStyles.remove(); | |
| } | |
| }); | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment