JavaScript/CSS/HTML || Placeholder.js – Simple Animated Floating Label For Textbox, Dropdown & Textarea Using Vanilla JavaScript
The following is a module which allows for a simple animated floating placeholder label for textbox, dropdown & textarea using vanilla javascript.
No special HTML markup is required.
Contents
1. Basic Usage
2. Placeholder HTML
3. Placeholder.js & CSS Source
4. More Examples
1. Basic Usage
Syntax is very straightforward. The following demonstrates adding and removing floating placeholders to elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Add & Remove Floating Placeholders. <script> (() => { // Add floating placeholder. It accepts either a string selector // or one or more Javascript elements. Placeholder.float('input:not([type="radio"]):not([type="checkbox"]), select, textarea'); // Remove floating placeholder. It accepts either a string selector // or one or more Javascript elements. Placeholder.remove(document.querySelectorAll('input:not([type="radio"]):not([type="checkbox"]), select, textarea')); })(); </script> |
‘Placeholder.float‘ and ‘Placeholder.remove‘ accepts either a string selector or one or more Javascript elements.
2. Placeholder HTML
The following is sample HTML used for the floating placeholder label. No special HTML markup is required. Simply supply an element with a ‘placeholder‘ attribute, and you’re all set!
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- // Sample HTML --> <input type="text" placeholder="Name" /> <input type="email" placeholder="Email" /> <input type="password" placeholder="Password" /> <select name="gender" id="gender" placeholder="Gender" > <option value="" selected></option> <option value="male">Male</option> <option value="female">Female</option> <option value="na">Prefer Not To Say</option> </select> <textarea rows="4" cols="50" placeholder="Describe Yourself"></textarea> |
3. Placeholder.js & CSS Source
The following is the Placeholder.js Namespace & CSS Source. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
// ============================================================================ // Author: Kenneth Perkins // Date: Sept 9, 2020 // Taken From: http://programmingnotes.org/ // File: Placeholder.js // Description: Module that adds a floating placeholder label to an element // Example: // // Add Placeholder // Placeholder.float('selector') // // // Remove Placeholder // Placeholder.remove('selector') // ============================================================================ /** * NAMESPACE: Placeholder * USE: Handles Placeholder related functions */ var Placeholder = Placeholder || {}; (function(namespace) { 'use strict'; // -- Public data -- // Property to hold public variables and functions let exposed = namespace; // Set class names and other shared data const settings = { attributePlaceholder: 'placeholder', // Element class names classNameFloatingItem: '.floating-placeholder', classNameContainer: '.floating-placeholder-container', classNamePlaceholder: '.floating-placeholder-label', classNameActive: '.active', // Element data names dataNamePlaceholderCache: 'data-placeholder-cache', cleanClassName: (str) => { return str ? str.trim().replace('.', '') : ''; }, }; exposed.settings = settings; /** * FUNCTION: float * USE: Adds a floating placeholder to the selected elements. * @param element: One or more JavaScript element to add floating placeholder to. * @return: N/A. */ exposed.float = (element) => { let items = verifyElements(element); for (const item of items) { addPlaceholder(item); } } /** * FUNCTION: remove * USE: Removes a floating placeholder from the selected elements. * @param element: One or more JavaScript element to remove floating placeholder from. * @return: N/A. */ exposed.remove = (element) => { let items = verifyElements(element); for (const item of items) { removePlaceholder(item); } } // -- Private data -- let removePlaceholder = (element) => { let container = getContainer(element); let parentNode = container.parentNode; removeClass(element, settings.classNameFloatingItem); let placeholderText = getPlaceholderTextCache(element); setPlaceholderText(element, placeholderText); setPlaceholderTextCache(element, null); getEvents().forEach(eventInfo => { eventInfo.names.forEach(eventName => { element.removeEventListener(eventName, eventInfo.callback); }); }); parentNode.insertBefore(element, container); parentNode.removeChild(container); } let addPlaceholder = (element) => { addClass(element, settings.classNameFloatingItem); let placeholderText = verifyPlaceholderText(element); let container = getContainer(element) || createContainer(element); let placeholder = getPlaceholder(element) || createPlaceholder(container); placeholder.innerHTML = placeholderText; placeholder.htmlFor = element.id; getEvents().forEach(eventInfo => { registerEvents(element, eventInfo.names, eventInfo.callback); }); if (!isEmpty(element.value)) { floatPlaceholder(element); } else { resetPlaceholder(element); } setDetectChangeHandler(element); } let setDetectChangeHandler = (element, property = 'value') => { let elementPrototype = Object.getPrototypeOf(element); if (!elementPrototype.hasOwnProperty(property)) { return; } let descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property); let newProps = { get: function () { return descriptor.get.apply(element, arguments); }, set: function (t) { setTimeout( () => { element.dispatchEvent(new Event(property + 'change')); }, 10); return descriptor.set.apply(element, arguments); } }; Object.defineProperty(element, property, newProps); } let floatPlaceholder = (element) => { let placeholder = getPlaceholder(element); if (!isNull(placeholder)) { addClass(placeholder, settings.classNameActive); } } let resetPlaceholder = (element) => { let placeholder = getPlaceholder(element); if (!isNull(placeholder)) { if (isEmpty(element.value)) { removeClass(placeholder, settings.classNameActive); } } } let getContainer = (element) => { return element.closest(settings.classNameContainer); } let getPlaceholder = (element) => { let container = getContainer(element); return !isNull(container) ? container.querySelector(settings.classNamePlaceholder) : null; } let createPlaceholder = (container) => { let placeholder = document.createElement('label'); addClass(placeholder, settings.classNamePlaceholder); container.appendChild(placeholder); return placeholder; } let createContainer = (element) => { let container = document.createElement('div'); let parentNode = element.parentNode; addClass(container, settings.classNameContainer); parentNode.insertBefore(container, element); container.appendChild(element); return container; } let verifyPlaceholderText = (element) => { if (isEmpty(element.id)) { element.id = `floating_placeholder_${randomFromTo(1271991, 7281987)}`; } let placeholderText = getPlaceholderText(element); if (!isEmpty(placeholderText)) { setPlaceholderTextCache(element, placeholderText); } setPlaceholderText(element, null); return getPlaceholderTextCache(element); } let setPlaceholderText = (element, value) => { addData(element, {key: settings.attributePlaceholder, value: value}); } let getPlaceholderText = (element) => { let value = getData(element, settings.attributePlaceholder); return value; } let setPlaceholderTextCache = (element, value) => { addData(element, {key: settings.dataNamePlaceholderCache, value: value}); } let getPlaceholderTextCache = (element) => { let value = getData(element, settings.dataNamePlaceholderCache); return value; } let floatPlaceholderEvent = (event) => { let element = event.currentTarget; let nodeName = element.nodeName.toLowerCase(); switch (event.type) { case 'focus': if (nodeName === 'select') { return; } break; case 'keyup': if (nodeName === 'select') { if (isEmpty(element.value)) { return; } } else { return; } break; } floatPlaceholder(element); } let resetPlaceholderEvent = (event) => { let element = event.currentTarget; let nodeName = element.nodeName.toLowerCase(); switch (event.type) { case 'keyup': if (nodeName === 'select') { if (!isEmpty(element.value)) { return; } } else { return; } break; } resetPlaceholder(element); } let registerEvents = (element, eventNames, func) => { eventNames.forEach((eventName, index) => { element.removeEventListener(eventName, func); element.addEventListener(eventName, func); }); } let addClass = (element, cssClass) => { cssClass = settings.cleanClassName(cssClass); let modified = false; if (cssClass.length > 0 && !hasClass(element, cssClass)) { element.classList.add(cssClass) modified = true; } return modified; } let removeClass = (element, cssClass) => { cssClass = settings.cleanClassName(cssClass); let modified = false; if (cssClass.length > 0 && hasClass(element, cssClass)) { element.classList.remove(cssClass); modified = true; } return modified; } let hasClass = (element, cssClass) => { cssClass = settings.cleanClassName(cssClass); return element.classList.contains(cssClass); } let isNull = (item) => { return undefined === item || null === item; } let isEmpty = (str) => { return isNull(str) || String(str).trim().length < 1; } let randomFromTo = (from, to) => { return Math.floor(Math.random() * (to - from + 1) + from); } let addData = (element, data) => { if (isNull(data)) { return; } else if (!Array.isArray(data)) { data = [data]; } data.forEach(item => { if (!isNull(item.value)) { element.setAttribute(item.key, item.value); } else { removeData(element, item); } }); } let removeData = (element, data) => { if (isNull(data)) { return; } else if (!Array.isArray(data)) { data = [data]; } data.forEach(item => { let key = item.key || item; element.removeAttribute(key); }); } let getData = (element, data) => { if (isNull(data)) { return null; } else if (!Array.isArray(data)) { data = [data]; } let results = []; data.forEach(item => { let key = item.key || item; results.push(element.getAttribute(key)); }); return results.length == 1 ? results[0] : results; } let isString = (item) => { return 'string' === typeof item; } let verifyElements = (items) => { if (isNull(items)) { throw new TypeError('No elements specified'); } else if (isString(items)) { items = document.querySelectorAll(items); } if (!isArrayLike(items)) { items = [items]; } return items; } // see if it looks and smells like an iterable object, and do accept length === 0 let isArrayLike = (item) => { return ( Array.isArray(item) || (!!item && typeof item === "object" && typeof (item.length) === "number" && (item.length === 0 || (item.length > 0 && (item.length - 1) in item) ) ) ); } let getEvents = () => { return [ {names: ['click', 'focus', 'keyup', 'valuechange'], callback: floatPlaceholderEvent}, {names: ['blur', 'focusout', 'keyup', 'valuechange'], callback: resetPlaceholderEvent}, ]; } (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Placeholder)); // http://programmingnotes.org/ |
The following is Placeholder.css.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
/* // ============================================================================ // Author: Kenneth Perkins // Date: Sept 9, 2020 // Taken From: http://programmingnotes.org/ // File: Placeholder.css // Description: CSS for the floating placeholder // ============================================================================ */ @import url('https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100'); .floating-placeholder { align-self: flex-end; } .floating-placeholder:focus { border: none; outline:none; background-color: #fff9e5; border-bottom: 1px solid orangered; } .floating-placeholder-label { position: absolute; top: 0; left: 0; font-size: 16px; pointer-events: none; transition: all 150ms ease-in-out; font-family: inherit; } .floating-placeholder-label.active { top: -12.5px; left: -9px; font-size: 11px; font-style: italic; } .floating-placeholder-container { position: relative; margin-bottom: 25px; display: flex; color: #898d8d; font-family: "Roboto",sans-serif, Marmelad,"Lucida Grande",Arial,"Hiragino Sans GB",Georgia,"Helvetica Neue",Helvetica; } .floating-placeholder-container input, .floating-placeholder-container textarea, .floating-placeholder-container select { border: 0; border-bottom: 1px solid #767c7c; background: transparent; width: 100%; padding: 8px 0 5px 0.15em; font-size: 16px; font-family: inherit; color: black; } .floating-placeholder-container select { appearance: none; background-image: url("data:image/svg+xml;utf8,<svg fill='black' height='1' viewBox='0 0 30 30' width='1' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/><path d='M0 0h24v24H0z' fill='none'/></svg>"); background-size: 35px 35px; background-repeat: no-repeat; background-position-x: 100%; background-position-y: 50%; } .floating-placeholder-container select::-ms-expand { display: none; } .floating-placeholder-container select option { color: black; background-color: white; } /* // http://programmingnotes.org/ */ |
4. More Examples
Below are more examples demonstrating the use of ‘Placeholder.js‘. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<!-- // ============================================================================ // Author: Kenneth Perkins // Date: Sept 9, 2020 // Taken From: http://programmingnotes.org/ // File: placeholderDemo.html // Description: Demonstrates the use of Placeholder.js // ============================================================================ --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>My Programming Notes Placeholder.js Demo</title> <style> .main { text-align:center; margin-left:auto; margin-right:auto; } .inline { display:inline-block; } .center { display: flex; justify-content: center; align-items: center; } .container { width: 280px; border: 1px solid lightgrey; padding: 60px; border-radius: 10px; margin-top: 30px; background-color: #f9f9f9; box-shadow: 0 0 3px rgba(0,0,0,0.3); } body { background-image: url("https://images.pexels.com/photos/3116416/pexels-photo-3116416.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260"); background-position: center; background-origin: content-box; background-repeat: no-repeat; background-size: cover; min-height:100vh; } </style> <!-- // Include module --> <link type="text/css" rel="stylesheet" href="./Placeholder.css"> <script type="text/javascript" src="./Placeholder.js"></script> </head> <body> <div class="main"> My Programming Notes Placeholder.js Demo <div class="center"> <div class="container"> <input type="text" placeholder="Name" /> <input type="email" placeholder="Email" /> <input type="password" placeholder="Password" /> <select name="gender" id="gender" placeholder="Gender" > <option value="" selected></option> <option value="male">Male</option> <option value="female">Female</option> <option value="na">Prefer Not To Say</option> </select> <textarea rows="4" cols="50" placeholder="Describe Yourself"></textarea> </div> </div> </div> <script> document.addEventListener("DOMContentLoaded", function(eventLoaded) { // Add floating placeholder to the selected elements Placeholder.float('input:not([type="radio"]):not([type="checkbox"]), select, textarea'); // Remove floating placeholder to the selected elements //Placeholder.remove(document.querySelectorAll('input:not([type="radio"]):not([type="checkbox"]), select, textarea')); }); </script> </body> </html><!-- // http://programmingnotes.org/ --> |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply