bs_base-8.x-1.x-dev/js/floating-labels.js
js/floating-labels.js
/**
* @file floating-labels.js
*
* Adjust form element width based on floating label size.
*/
(function (Drupal, once) {
'use strict';
Drupal.behaviors.floatingLabels = {
attach: function attach(context) {
// Fixes the width of the form controls if the label is wider than the
// form control.
var elements = once('floating-label', '.form-item--floating-label:not(.form-no-label)', context);
elements.forEach(function (el, i) {
var control = el.querySelector('.form-control, .form-select');
var label = el.querySelector('label');
if (label && control.offsetWidth < label.offsetWidth) {
var paddingRight = parseFloat(window.getComputedStyle(control).getPropertyValue('padding-right'));
var adjustedWidth = label.offsetWidth + paddingRight;
// Respect maximum parent width (when controls are in the grid, etc).
if (adjustedWidth > el.offsetWidth) {
adjustedWidth -= paddingRight;
}
control.style.minWidth = adjustedWidth + 'px';
}
if (control.classList.contains('form-select')) {
// We need to add a helper class when the select changes, so we can
// style the floating labels.
control.addEventListener('change', function() {
if (this.value !== '') {
control.classList.add('select-filled');
}
else {
control.classList.remove('select-filled');
}
});
}
});
}
};
}(Drupal, once));
