Skip to content

Instantly share code, notes, and snippets.

@robert-michels
Last active March 23, 2021 02:03
Show Gist options
  • Select an option

  • Save robert-michels/27652e3e6cb30ac861fd8be6895d80df to your computer and use it in GitHub Desktop.

Select an option

Save robert-michels/27652e3e6cb30ac861fd8be6895d80df to your computer and use it in GitHub Desktop.
// CODE SNIPPET, NOT THE FULL FILE //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//__________________________________________________________ FLOATING LABEL TEXT INPUTS _________________________________________________________
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//For floating labels: User enters text into text input and label floats up.
const labelMod = "input__label--selected";
const labelModFloating = "input__label--floating"
//Each instance contains a label & a text input. The input listens for user inputs and styles the label.
//________________________________________________________________ Pair Class
var Pair = function(label, input) {
this.label = label;
this.input = input;
//add floating modifier
if (!this.label.classList.contains(labelModFloating)) this.label.classList.add(labelModFloating);
if (this.input.value !== "") if (!this.label.classList.contains(labelMod)) this.label.classList.add(labelMod);
this.input.addEventListener('input', (event) => {
this.label.classList.add(labelMod);
//console.log("Focus on: " + this.input.id + ", with label: " + this.label.innerHTML + ", text:" + event.target.value);
//Change label style on input
if (event.target.value === ""){
if (this.label.classList.contains(labelMod)) this.label.classList.remove(labelMod);
} else {
if (!this.label.classList.contains(labelMod)) this.label.classList.add(labelMod);
}
});
};
//Find all cells
var cells = [...document.querySelectorAll(".form__cell")];
//Create pair classes for each cell that contains exactly one label & one input
for (let i = 0; i < cells.length; i++) {
let cell = cells[i];
let labels = [...cell.querySelectorAll(".input__label")];
let inputs = [...cell.querySelectorAll(".input__text")];
if (labels.length === 1 && inputs.length === 1){
new Pair(labels[0], inputs[0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment