Styling a text box with JavaScript

I am completely new to JavaScript and would like to change the textbox of a form (which is generated by an external script) like this:

1.) Textarea at startup: marked "Your message here" in color "rgb (136, 136, 136)"

2.) Textarea on focus: label removed and color set to 'rgb (0, 0, 0)'

3.) Textarea on blur: user input color set to 'rgb (136, 136, 136)'; if there is no input, the label reappears in color 'rgb (136, 136, 136)'

I experimented with

var foo = document.getElementById('HCB_textarea');
foo.innerHTML = 'Your message here';
foo.style.color = 'rgb(136, 136, 136)';
foo.onfocus = do something;
foo.onblur = do something;

      

but didn't get it. TIA

+2


a source to share


2 answers


By assuming "label", you do not mean the HTML element of the label, but instead of the default text in the text string as your example seems, try this:



var foo = document.getElementById('HCB_textarea');
var defaultText = 'Your message here';
foo.value = defaultText;
foo.style.color = '#888';
foo.onfocus = function(){
    foo.style.color = '#000';
    if ( foo.value == defaultText ) {
        foo.value = '';
    }
};
foo.onblur = function(){
    foo.style.color = '#888';
    if ( foo.value == '' ) {
        foo.value = defaultText;
    }

};

      

0


a source


It looks pretty close to me. You have to color all or none of the textbox, you cannot color certain characters without some crazy hacks.

var foo = document.getElementById('HCB_textarea');
var labelVal = 'Your message here'
foo.value = origVal;
foo.style.color = 'rgb(136, 136, 136)';
foo.onfocus = function() {
  if( foo.value == labelVal ) foo.value = "";
  foo.style.color = 'rgb(136, 136, 136)';
}
foo.onblur = function() {
  if( foo.value != "" ) {
    foo.style.color = 'rgb(0, 0, 0)';
  } else {
    foo.value = labelVal;
    foo.style.color = 'rgb(136, 136, 136)';
  }
}
// You should modify this to use your actual form name.
document.forms[0].onsubmit = function() {
  if( foo.value == labelVal ) foo.value = "";
}

      




EDIT . I changed the code because Mario indicated that you wanted the label to be inside the textbox, not the element <label>

.

+1


a source







All Articles