Is there a method to achieve a floating label effect in Bootstrap 4 even after removing the "required" attribute from the input field?
$(document).ready(function() {
$('.form-group input').on('focus', function() {
$(this).siblings('label').addClass('active');
});
$('.form-group input').on('blur', function() {
if (!$(this).val() && !$(this).attr('required')) {
$(this).siblings('label').removeClass('active');
}
});
});
.appointment {
padding-top: 49px;
margin-bottom: 30px;
}
.form-group {
position: relative;
margin-bottom: 1.5rem;
}
a:hover {
color: blue;
transition: .5s;
}
.form-group input {
padding: 10px;
border: 1px solid #ced4da;
position: relative;
z-index: 1;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.form-group label {
position: absolute;
left: 15px;
top: 50%;
transform: translateY(-50%);
font-size: 1rem;
color: gray;
pointer-events: none;
transition: 0.2s ease-out all;
z-index: 2;
border: 1px solid transparent;
padding-left: 10px;
}
.form-group input:focus,
.form-group input:valid {
border-color: #ced4da;
box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}
.form-group input:focus+label,
.form-group input:valid+label {
top: 0;
font-size: 0.75rem;
color: #555;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<form>
<div class="form-group">
<div class="row">
<div class="col">
<input type="text" id="firstname" name="firstname" class="form-control" required>
<label for="firstname">First Name</label>
</div>
<div class="col">
<input type="text" id="middlename" name="middlename" class="form-control">
<label for="middlename">Middle Name</label>
</div>
<div class="col">
<input type="text" id="lastname" name="lastname" class="form-control" required>
<label for="lastname">Last Name</label>
</div>
</div>
</div>
<div class="text-center">
<label>
<a href="{{ route('index') }}"><i class="icofont-bubble-left"></i> Back to Home</a>
</label>
</div>
<br>
</form>
I am encountering an issue with my script where the label is already floating even when the input field is not focused or reloaded. I'm unsure what might be causing this behavior.