Highlight related label when input has focus
The <label> tag defines a label for an input element.
The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.
The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control. With the script below you can add an extra improvement to your form. Now when an input field has the focus the corresponding label will be highlighted.
//add JavaScript events as arrays,
//so you can add multiple events to a component
function frmAddListener(element, event, listener, bubble) {
if (element.addEventListener) {
if (typeof (bubble) == "undefined")
bubble = true;
element.addEventListener(event, listener, bubble);
} else if (this.attachEvent) {
element.attachEvent("on" + event, listener);
}
}
function frmInitOverLabels() {
if (!document.getElementById)
return;
var labels, id, field;
labels = document.getElementsByTagName('label');
for ( var i = 0; i < labels.length; i++) {
// Skip labels that do not have a named association
// with another field.
id = labels[i].htmlFor || labels[i].getAttribute('for');
if (!id || !(field = document.getElementById(id))) {
continue;
}
// Set handlers to show and hide labels.
frmAddListener(field, "focus", function(e) {
if (!e)
var e = window.event;
if (e.target)
targ = e.target.id;
if (e.srcElement)
targ = e.srcElement.id;
frmHighlightLabel(targ, true);
});
frmAddListener(field, "blur", function(e) {
if (!e)
var e = window.event;
if (e.target)
targ = e.target.id;
if (e.srcElement)
targ = e.srcElement.id;
frmHighlightLabel(targ, false);
});
// Handle clicks to label elements (for Safari).
frmAddListener(labels[i], "click", function() {
var id, field;
id = this.getAttribute('for');
if (id && (field = document.getElementById(id))) {
field.focus();
}
});
}
}
function frmHighlightLabel(field_id, blink) {
var field_for;
var labels = document.getElementsByTagName('label');
for ( var i = 0; i < labels.length; i++) {
field_for = labels[i].htmlFor || labels[i].getAttribute('for');
if (field_for == field_id) {
if (blink) {
labels[i].tmpColor = labels[i].style.color;
labels[i].style.color = "#0167a9";
} else {
labels[i].style.color = labels[i].tmpColor;
}
return true;
}
}
}
frmAddListener(window, "load", function() {
frmInitOverLabels()
});
The JQuery code for highlighting related label when input has focus.
$("form :input").focus(function() {
$("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
$("label").removeClass("labelfocus");
});
<html> <head> </head> <body> <label for="name"/><input type="text" name="name"/> </body> </html>