0

I have a website with a bunch of inputs that looks like this (I cannot edit the HTML since this part is automatically generated):

<div style="display: inline; position: relative;">
    <div>
        <label for="inputID">label here</label>
        <label >*</label>
    </div>
    <div>
        <div>
            <input type="text" fieldformat="None" id="inputID" placeholder="something">
        </div>
    </div>
</div>

I want to make it so that when the user is entering something on input field, the label will disappear appear

 ___________________________             _first name (label)_______
| first name (placeholder)  |  click    |                          |
|___________________________| --------> |__________________________|

here is my attempt at doing it with javascript:

function displayOnFocusAndOnFocusOut() {
    var inputs = [
        'inputID1',
        'inputID2',
        'inputID3',
        ...
    ]
    for(var i = 0; i < inputs.length; i++) {
        var input = document.getElementById(inputs[i])
        input.onfocus = function() {
            input.parentElement.parentElement.parentElement.firstChild.style.display = 'none'
            console.log(input.parentElement.parentElement.parentElement.firstChild)
        }
        input.onfocusout = function() {
            input.parentElement.parentElement.parentElement.firstChild.style.display = 'block'
        }
    }
}

However this doesnt work as the label still displays when I click on the input, and with a console log it shows that only the last input is affected. I've also tried adding !important but it still does not work.

How can I fix this?

Thanks

qwerty_99
  • 640
  • 5
  • 20

1 Answers1

0

You don't need any javascript:

body {
  height: 200vh;
}

.field>div {
  display: inline-flex;
  flex-direction: column-reverse;
}

.label {
  height: 1em;
  margin-bottom: 0.2em;
}

.label>label {
  transition: height 0.5s;
  height: 0;
  overflow: hidden;
  display: inline-block;
}

.field input:not(:placeholder-shown) ~.label>label {
  height: 1em;
}
<div class="field">
  <div>
    <input type="text" fieldformat="None" id="inputID1" placeholder="something">
    <div class="label"><label>label here *</label></div>
  </div>
</div>
<br>
<div class="field">
  <div>
    <input type="text" fieldformat="None" id="inputID2" placeholder="something">
    <div class="label"><label>label here *</label></div>
  </div>
</div>

This example will show labels when placeholder is hidden, you can change it so it would show labels when input field is in focus by replacing :not(:placeholder-shown) with :focus

vanowm
  • 9,466
  • 2
  • 21
  • 37