Question

For some reason the onblur and onfocus properties don't work. Am I defining them right?

var replyTxt = document.createElement("input");
    replyTxt.id="replyTxt";
    replyTxt.type="text";
    replyTxt.value="Write a reply";

    replyTxt.onfocus = function(){if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';};
    replyTxt.onblur= function(){if(replyTxt.value=='') replyTxt.value=replyTxt.defaultValue;};

I have also tried putting "function(){if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';}" in quotations

Was it helpful?

Solution

The events work - so there may be a problem with your logic...

if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';

Where do you set replyTxt.defaultValue? In your example, you don't - so the logic will never fire. Try this...

var replyTxtDefaultText = "Write a reply";
var replyTxt = document.createElement("input");
    replyTxt.id="replyTxt";
    replyTxt.type="text";
    replyTxt.value=replyTxtDefaultText;

    replyTxt.onfocus = function(){if(replyTxt.value==replyTxtDefaultText) replyTxt.value='';};
    replyTxt.onblur= function(){if(replyTxt.value=='') replyTxt.value=replyTxtDefaultText;};

OTHER TIPS

Just a hint: try replacing replyTxt with this in your event functions.

try setAttribute. more information about function take a look this link

var replyTxt = document.createElement("input");
replyTxt.setAttribute('onFocus', 'focusFunction()');

function focusFunction()
{
   if(replyTxt.value==replyTxtDefaultText) 
      replyTxt.value='';
}

And make sure you append it to something.

<form id="x">
</form>
<script>
window.onload=function() {
  var replyTxt = document.createElement("input");
  replyTxt.id="replyTxt";
  replyTxt.type="text";
  replyTxt.value=replyTxt.defaultValue="Write a reply";
  replyTxt.onfocus = function(){if(this.value==this.defaultValue) this.value='';};
  replyTxt.onblur= function(){if(this.value=='') this.value=this.defaultValue;};

  document.getElementById('x').appendChild(replyTxt);
}
</script>

Actually I was working on a similar problem as a homework and I found out that is better to clear the field as soon as the mouse lands on the field rather than making a comparison if left untouched and then clear it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top