I am trying to re-create or immitate (HTML's) placeholder behaviour using javascript (and jQuery).
Could anyone please tell me how I would achieve this? I tried using the following code:
$(document).ready(function () {
//On init:
var initPlaceholderTxt = $("p").text();
//Execution:
//Using this, placeholder will not display correct information,
//lacking a previous clicked character:
$("#test").on("keydown", function (event) {
var value = $(this).val();
$("p").text(value);
});
/*
//Core feature:
$("#test").keyup(function() {
var value = $( this ).val();
if(value != null && value != "") {
$("p").text(value);
}
else {
$("p").text(initPlaceholderTxt);
}
});
//Make characters appear more dynamically or faster:
$("#test").keydown(function() {
var value = $( this ).val();
$("p").text(value);
});
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<p>Placeholder text</p>
<textarea placeholder="example"></textarea>
I got the main part working, however I am trying to make it more dynamic. When a user types something into a default input with a placeholder defined, the moment a key has been pressed down, a character will appear in the box and the placeholder will disappear. This last part does not seem to happen with my current code.
As I press a key down, the placeholder already tries to change its text value before a new character has been added to the input.
Most would say that a solution to this would be the usage of keyup
. However there is a downside of using keyup
as well, as it is not making characters dynamically appear right of the bat when pressing a key. Please let me know how to solve this.
Edit: The bottom text area is an example to show the intended behaviour. The paragraph element is supposed to act/behave like (any) placeholder text which you see in the example.