dchacke dchacke - 22 days ago 7
jQuery Question

jquery set cursor to first character of textarea

I have custom placeholders in a textarea and I would like every browser to move the cursor to the first character of that placeholder as soon as the user clicks it or focuses in on it.

How can I achieve that? I have no idea so no code posted.

Thanks!

Dennis

EDIT 1

This is the textarea:

<textarea id="posttext"> Post something...</textarea><br/>


And this is the code to remove " Post something...":

//Placeholder in posttext
$('#posttext').keydown(function(){
if($(this).val()==' Post something...') $(this).val('').css('color','black');
}).blur(function(){
if($(this).val()=='') $(this).val(' Post something...').css('color','grey');
});

Answer

$('#posttext').on('focus', function() {
    if($(this).val() == ' Post something...') {
        $(this).val('').css('color','black');
    }
}).blur(function() {
    if($(this).val() == '') {
        $(this).val(' Post something...').css('color','grey');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="posttext"> Post something...</textarea>