The natural/modern solution for this is using placeholder
.
<input placeholder="nome" />
However placeholder is HTML5 and some older browsers do not support. How to do then? here is an alternative:
If you want to use the keydown
, that is when the user starts writing, you can do so by comparing the value attribute with the real value that he has at the moment:
var input = document.querySelector('input');
input.addEventListener('keydown', function (e) {
var original = this.getAttribute('value');
var novo = this.value;
if (novo == original) this.value = '';
});
The .getAttribute('value');
is always the same as in HTML. What is dynamic and changes depending on what is written is the property .value
. So you can know if what’s in the input is still the original.
And how do you differentiate "start writing" from a normal input? In other words, if you already have content, how long does it take to be considered "start"? The fields are already filled in, is that it? in this case a
placeholder
would be more correct. Explain a little better and join code to understand your problem.– Sergio
@Sergio, the fields are already written... type: <input value="name"/> ... when the user writes the first letter, this value "name", is deleted...
– Andrei Coelho
Andrei, have you tested using a placeholder? ->
<input placeholder="nome" />
– Sergio
No... I’m gonna test
– Andrei Coelho
@Sergio, thank you very much! I hadn’t even heard of it... Hug!
– Andrei Coelho
Andrei, great, I’ll add an answer to that
– Sergio