Hello. I invent a bicycle (animated placeholder). I just can’t figure out how to keep the initial value value, so that it pops up both with an empty input and with a full one. He did it a little differently, while the new value entered into the input popped up instead of the desired one (E-mail, Phone). How to fix it? Yes, it is important to use the value, not the placeholder, since need IE8 support.
I know that there are already solutions on jQuery, but I want my bike).
(function animatePlaceholder() { var input = document.querySelectorAll('.input-box input[type="text"]'); [].forEach.call(input, function(elem) { var span = document.createElement('span'), value; elem.onfocus = function() { value = this.value; span.innerHTML = value; this.parentNode.insertBefore(span, this); this.value = ''; span.classList.add('placeholder'); span.classList.add('placeholder-show'); } elem.onblur = function() { span.classList.remove('placeholder-show'); this.value = value; } }); }());
* { box-sizing: border-box; } .input-box { display: block; padding-top: 15px; position: relative; font-size: 15px; } .input-box input[type="text"] { height: 25px; padding: 0 5px; font-size: 13px; color: silver; } input[type="text"]:focus { outline: none; } .placeholder { display: inline-block; position: absolute; top: 20px; left: 5px; transition-duration: .5s; z-index: -100; font-size: 16px; color: silver; } .placeholder-show { top: 0; left: 0; font-size: 13px; z-index: 100; color: silver; }
<div class="input-box"> <input type="text" value="E-mail" /> </div> <div class="input-box"> <input type="text" value="Phone" /> </div>