Moving Placeholder on Focus with HTML, CSS & JavaScript
12/17/2020
Demo
Code
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Moving Placeholder on Focus</title>
<link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
<link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form class="form">
<input id="formInput" class="form__input" type="text" name="text">
<label id="formPlaceholder" class="form__placeholder">Placeholder</label>
</form>
</div>
</body>
</html>
CSS
@charset "utf-8";
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 16px;
}
body {
background-color: #e6d37e;
font-family: futura-pt, sans-serif;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
display: flex;
justify-content: center;
align-items: center;
position: relative;
width: 100%;
height: 100vh;
padding: 20px;
}
.form {
position: relative;
width: 100%;
max-width: 400px;
}
.form__input {
width: 100%;
height: 50px;
padding: 0 10px;
border: none;
border-bottom: 2px solid #10660d;
background-color: #f8f8ec;
font-size: 1.125rem;
outline: none;
}
.form__placeholder {
position: absolute;
top: 15px;
left: 10px;
color: #ccc;
font-size: 1.125rem;
transition: .4s;
}
.form__placeholder.moved {
top: -20px;
left: 0;
color: #10660d;
font-size: 1rem;
}
JavaScript
var formInput = document.getElementById("formInput");
var formPlaceholder = document.getElementById("formPlaceholder");
formInput.addEventListener('focusin', () => {
if(formInput.value.length === 0) {
formPlaceholder.classList.add("moved");
}
});
formInput.addEventListener('focusout', () => {
if(formInput.value.length === 0) {
formPlaceholder.classList.remove("moved");
} else {
formPlaceholder.classList.add("moved");
}
});