Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop label from blocking user input inside of input element

Tags:

css

In the following simplified example I use absolute positioning to place a label inside of an input element. I use JavaScript to make the label shrink or grow depending on focus / blur. This works as expected.

My question: If I click the text label it blocks focus on the input element and the label doesn't shrink. If I click anywhere else inside of the element it works as expected. I tried Z-index -1 to place the label behind the input box but that didn't solve the problem. I also tried user-select: none but it still blocked focus on the input element. Is there a way to stop the label from blocking the input element?

document.querySelector('input').addEventListener('focus', labelShrink);
document.querySelector('input').addEventListener('blur', labelGrow);

function labelShrink() {
    document.querySelector('.inputLabel').style.fontSize = ".75rem";
}

function labelGrow() {
    if (!document.querySelector('.inputField').value) {
        document.querySelector('.inputLabel').style.fontSize = "1.5rem";
    } 
}
.inputContainer {
    position: relative;
}

.inputLabel {
    position: absolute;
    z-index = -1; 
    padding: .25rem 0 0 .25rem;
    font-size: 1.5rem;
    user-select: none;
    transition: font-size .25s;
}

.inputField {
    padding: .75rem 0 0 0;
    font-size: 2rem;
    background-color: transparent;
}
<div class="inputContainer">
  <label class="inputLabel" for="userName">User Name</label>
  <input class="inputField" type="text" name="userName">
</div>
like image 390
DR01D Avatar asked Oct 19 '25 21:10

DR01D


1 Answers

Add pointer-events: none; to the label so you can click trough it.

document.querySelector('input').addEventListener('focus', labelShrink);
document.querySelector('input').addEventListener('blur', labelGrow);

function labelShrink() {
    document.querySelector('.inputLabel').style.fontSize = ".75rem";
}

function labelGrow() {
    if (!document.querySelector('.inputField').value) {
        document.querySelector('.inputLabel').style.fontSize = "1.5rem";
    } 
}
.inputContainer {
    position: relative;
}

.inputLabel {
    position: absolute;
    z-index = -1; 
    padding: .25rem 0 0 .25rem;
    font-size: 1.5rem;
    user-select: none;
    transition: font-size .25s;
    pointer-events: none; // Add this line
}

.inputField {
    padding: .75rem 0 0 0;
    font-size: 2rem;
    background-color: transparent;
}
<div class="inputContainer">
  <label class="inputLabel" for="userName">User Name</label>
  <input class="inputField" type="text" name="userName">
</div>
like image 191
SuperDJ Avatar answered Oct 22 '25 02:10

SuperDJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!