dchacke dchacke - 1 year ago 65
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.




This is the textarea:

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

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

//Placeholder in posttext
if($(this).val()==' Post something...') $(this).val('').css('color','black');
if($(this).val()=='') $(this).val(' Post something...').css('color','grey');

Answer Source

$('#posttext').on('focus', function() {
    if($(this).val() == ' Post something...') {
}).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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download