Online Shopping : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

20 of 22 people (91%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How do I change the style of a form field label when the field gets focus?
How do I change the style of a form field label when the field gets focus?

Sep 13th, 2000 06:50
Martin Honnen,


In NN6 and IE4+ this is quite easy, just stuff the form field label 
into a SPAN (or for an IE4+ and NN6 only solution use a LABEL element) 
and change the style class of the SPAN (or LABEL) e.g.
  document.all.spanID.className = 'styleClassName'
for IE4+ and
  document.getElementById('spanID').className = 'styleClassName'
for NN6. 
For NN4 you can't change the style class of an element but need to take 
several steps. Position the SPAN to be able to rewrite it, implement 
code to rewrite the SPAN and furthermore change your page layout as the 
positioning of the SPAN forces you to break up your form into several 
ones. Here is a complete example:
<HTML>
<HEAD>
<STYLE>
#aLayer, #a2ndLayer {
  position: relative;
}
.bold {
  font-weight: bold;
}
.red {
  color: red;
}
</STYLE>
<SCRIPT>
function setStyle (id, content, className) {
  if (document.all)
    document.all[id].className = className;
  else if (document.getElementById)
    document.getElementById(id).className = className;
  else if (document.layers) {
    var l = document[id];
    if (!l.ol) {
      var ol = l.ol = new Layer(window.innerWidth);
      ol.left = l.pageX;
      ol.top = l.pageY;
      ol.visibility = 'show';
      l.visibility = 'hide';
    }
    var ol = l.ol;
    ol.document.open();
    ol.document.write('<SPAN CLASS="' + className + '">' + content 
+ '<\/SPAN>');
    ol.document.close();
  }
  setTimeout('unsetStyle("' + id + '","' + content + '")', 2000);
}
function unsetStyle (id, content) {
  if (document.all)
    document.all[id].className = '';
  else if (document.getElementById)
    document.getElementById(id).className = '';
  else if (document.layers) {
    var ol = document[id].ol;
    ol.document.open();
    ol.document.write(content);
    ol.document.close();
  }
}
</SCRIPT>
</HEAD>
<BODY>
<SPAN ID="aLayer">
Enter GOD's name:
</SPAN>
<FORM>
<INPUT TYPE="text" NAME="god" VALUE="Kibo"
       ONFOCUS="setStyle('aLayer', 'Enter GOD\'s name:', 'bold')"
>
</FORM>
<SPAN ID="a2ndLayer">
Enter your name:
</SPAN>
<FORM>
<INPUT TYPE="text" NAME="god"
       ONFOCUS="setStyle('a2ndLayer', 'Enter your name:', 'red')"
>
</FORM>
</BODY>
</HTML>