How do I auto-hide placeholder text upon focus using css or jquery?
Asked Answered
P

28

272

This is done automatically for every browser except Chrome.

I'm guessing I have to specifically target Chrome.

Any solutions?

If not with CSS, then with jQuery?

Playbill answered 14/3, 2012 at 17:31 Comment(5)
cehck my edit then, it might helpMeshwork
Opera is also another browser which removes placeholder on focus.Gratia
Firefox as of version 15 no longer removes the placeholder text until you start typing. I believe the same may be the case for IE10 but I don't have a way to verify that.Disused
I am concerned that nobody mentioned the fact that you shouldn't bother modifying native browser behaviors. I for one prefer that the placeholder remains present. It just helps me as an end user, and it's a feature that browsers are now starting to implement... probably because the disappear-on-focus behavior proved to be a usability problem. Let the browser be, please.Hyoscyamus
"This is done automatically for every browser except Chrome." Not anymore? I've just tried this on OSX in Firefox 37.0.2, Safari 7.1.5, and Chrome 42.0. None of them remove the placeholder text until I start typing, and all of them put it back when I clear the field.Gully
C
298
<input 
type="text" 
placeholder="enter your text" 
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'enter your text'" />
Chausses answered 14/3, 2012 at 17:35 Comment(6)
This makes it go but when I click away from the field it remains blank.Playbill
@LondonGuy: Just edited my post, see if it works like you wanted. But Toni Michel Caubet solution is nicerChausses
The problem here is this is obtrusive JavaScript. Toni Michel Caubet's solution is better.Riddance
I like it, but unfortunately it doesn't work neither IE nor Safari.Burrton
not working. stackblitz.com/edit/angular-jd2l6y-frudzk?file=app/…Noodle
Better to never, ever use inline handlers. They have way too many problems to be worth using nowadays.Rastus
D
621

Edit: All browsers support now

input:focus::placeholder {
  color: transparent;
}
<input type="text" placeholder="Type something here!">

Firefox 15 and IE 10+ also supports this now. To expand on Casey Chu's CSS solution:

input:focus::-webkit-input-placeholder { color:transparent; }
input:focus:-moz-placeholder { color:transparent; } /* FF 4-18 */
input:focus::-moz-placeholder { color:transparent; } /* FF 19+ */
input:focus:-ms-input-placeholder { color:transparent; } /* IE 10+ */
Disused answered 3/9, 2012 at 14:48 Comment(7)
Great answer! I don't see much sense in abandoning my old jQuery solution in favor of HTML5 and then go right ahead and add the JavaScript back in as a fix. This is just the solution I was looking for.Kidwell
@MartinHunt have you tried this on FF? input:focus::-moz-placeholderStreetwalker
Apologies for dredging up an old thread, but just to make this more complete: input:focus:-moz-placeholder is for Firefox 18 and below, for 19 onwards you need to use: input:focus::-moz-placeholder (note the double colon). Ref: css-tricks.com/snippets/css/style-placeholder-textGilges
this comment is a win. works with dynamic controls, like kendo tooTergum
on printing in chrome doesn't work... any help input[type=text].form-control::-webkit-input-placeholder, input[type=textarea].form-control::-webkit-input-placeholder { color: #FFFFFF; }Braggadocio
Great answer also from me! For those of us who might also require this functionality when the field is disabled here is the CSS code: /* Hiding the placeholder text (if any), when the holding field is disabled */ input:disabled::-webkit-input-placeholder { color:transparent; } input:disabled:-moz-placeholder { color:transparent; } input:disabled::-moz-placeholder { color:transparent; } input:disabled:-ms-input-placeholder { color:transparent; }Torrell
visibility: hidden makes more sense to me. Using a transparent color is too hacky.Vermeil
C
298
<input 
type="text" 
placeholder="enter your text" 
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'enter your text'" />
Chausses answered 14/3, 2012 at 17:35 Comment(6)
This makes it go but when I click away from the field it remains blank.Playbill
@LondonGuy: Just edited my post, see if it works like you wanted. But Toni Michel Caubet solution is nicerChausses
The problem here is this is obtrusive JavaScript. Toni Michel Caubet's solution is better.Riddance
I like it, but unfortunately it doesn't work neither IE nor Safari.Burrton
not working. stackblitz.com/edit/angular-jd2l6y-frudzk?file=app/…Noodle
Better to never, ever use inline handlers. They have way too many problems to be worth using nowadays.Rastus
M
87

Here is a CSS-only solution (for now, only works in WebKit):

input:focus::-webkit-input-placeholder {
    opacity: 0;
}
Margret answered 12/8, 2012 at 8:10 Comment(2)
I like this answer, but the browser support for this just isn't there yet.Balaton
Thank you so much for such an elegant solution that frees you from logic.Swami
O
64

Pure CSS Solution (no JS required)

Building on @Hexodus and @Casey Chu's answers, here is an updated and cross-browser solution that leverages CSS opacity and transitions to fade the placeholder text out. It works for any element that can use placeholders, including textarea and input tags.

::-webkit-input-placeholder { opacity: 1; -webkit-transition: opacity .5s; transition: opacity .5s; }  /* Chrome <=56, Safari < 10 */
:-moz-placeholder { opacity: 1; -moz-transition: opacity .5s; transition: opacity .5s; } /* FF 4-18 */
::-moz-placeholder { opacity: 1; -moz-transition: opacity .5s; transition: opacity .5s; } /* FF 19-51 */
:-ms-input-placeholder { opacity: 1; -ms-transition: opacity .5s; transition: opacity .5s; } /* IE 10+ */
::placeholder { opacity: 1; transition: opacity .5s; } /* Modern Browsers */
    
*:focus::-webkit-input-placeholder { opacity: 0; } /* Chrome <=56, Safari < 10 */
*:focus:-moz-placeholder { opacity: 0; } /* FF 4-18 */
*:focus::-moz-placeholder { opacity: 0; } /* FF 19-50 */
*:focus:-ms-input-placeholder { opacity: 0; } /* IE 10+ */
*:focus::placeholder { opacity: 0; } /* Modern Browsers */
<div>
  <div><label for="a">Input:</label></div>
  <input id="a" type="text" placeholder="CSS native fade out this placeholder text on click/focus" size="60">
</div>

<br>

<div>
  <div><label for="b">Textarea:</label></div>
  <textarea id="b" placeholder="CSS native fade out this placeholder text on click/focus" rows="3"></textarea>
</div>

Revisions

  • Edit 1 (2017): Updated to support modern browsers.
  • Edit 2 (2020): Added the runnable Stack Snippet.
Offence answered 1/10, 2015 at 13:26 Comment(2)
The best CSS solution!Preglacial
Good old CSS... great simple solution! Why didn't I think of that??Shears
M
43

have you tried placeholder attr?

<input id ="myID" type="text" placeholder="enter your text " />

-EDIT-

I see, try this then:

$(function () {

    $('#myId').data('holder', $('#myId').attr('placeholder'));

    $('#myId').focusin(function () {
        $(this).attr('placeholder', '');
    });
    $('#myId').focusout(function () {
        $(this).attr('placeholder', $(this).data('holder'));
    });


});

Test: http://jsfiddle.net/mPLFf/4/

-EDIT-

Actually, since placeholder should be used to describe the value, not the name of the input. I suggest the following alternative

html:

<label class="overlabel"> 
    <span>First Name</span>
    <input name="first_name" type="text" />
</label>

javascript:

$('.overlabel').each(function () {
    var $this = $(this);
    var field = $this.find('[type=text], [type=file], [type=email], [type=password], textarea');
    var span = $(this).find('> span');
    var onBlur = function () {
        if ($.trim(field.val()) == '') {
            field.val('');
            span.fadeIn(100);
        } else {
            span.fadeTo(100, 0);
        }
    };
    field.focus(function () {
        span.fadeOut(100);
    }).blur(onBlur);
    onBlur();
});

css:

.overlabel {
  border: 0.1em solid;
  color: #aaa;
  position: relative;
  display: inline-block;
  vertical-align: middle;
  min-height: 2.2em;
}
.overlabel span {
  position: absolute;
  left: 0;
  top: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.overlabel span, .overlabel input {
  text-align: left;
  font-size: 1em;
  line-height: 2em;
  padding: 0 0.5em;
  margin: 0;
  background: transparent;
  -webkit-appearance: none; /* prevent ios styling */
  border-width: 0;
  width: 100%;
  outline: 0;
}

Test:

http://jsfiddle.net/kwynwrcf/

Meshwork answered 14/3, 2012 at 17:33 Comment(3)
Nice to see the data attribute being used. But I would look at the CSS equivalent. When cached it will be a faster solution and can be global. The above needs the data attribute to be placed on every element needed. (answer below)Menstruum
This is overcomplicated. Could be done with far less code.Caucasia
@Caucasia show me the light ( but i'm not sure if you have seen that there are 3 different solutions )Meshwork
P
19

To augment @casey-chu's and pirate rob's answer, here's a more cross browser compatible way:

    /* WebKit browsers */
input:focus::-webkit-input-placeholder { color:transparent; }

    /* Mozilla Firefox 4 to 18 */
input:focus:-moz-placeholder { color:transparent; }

    /* Mozilla Firefox 19+ */
input:focus::-moz-placeholder { color:transparent; }

    /* Internet Explorer 10+ */
input:focus:-ms-input-placeholder { color:transparent; }
Peculiarize answered 1/7, 2013 at 10:23 Comment(1)
Exactly what i have written now (instead i used opacity:0;)! The only CSS solution in this thread with all possible browser supports!Leslie
G
12

Toni's answer is good, but I'd rather drop the ID and explicitly use input, that way all inputs with placeholder get the behavior:

<input type="text" placeholder="your text" />

Note that $(function(){ }); is the shorthand for $(document).ready(function(){ });:

$(function(){
    $('input').data('holder',$('input').attr('placeholder'));
    $('input').focusin(function(){
        $(this).attr('placeholder','');
    });
    $('input').focusout(function(){
        $(this).attr('placeholder',$(this).data('holder'));
    });
})

Demo.

Gerund answered 26/7, 2012 at 13:29 Comment(1)
This doesn't work if you have more than one field. Here is enhanced version of your code jsfiddle.net/6CzRq/64Funest
S
9

I like to package this up in the name space and run on elements with the "placeholder" attribute...

$("[placeholder]").togglePlaceholder();

$.fn.togglePlaceholder = function() {
    return this.each(function() {
        $(this)
        .data("holder", $(this).attr("placeholder"))
        .focusin(function(){
            $(this).attr('placeholder','');
        })
        .focusout(function(){
            $(this).attr('placeholder',$(this).data('holder'));
        });
    });
};
Shirting answered 18/9, 2012 at 8:44 Comment(0)
B
5

Sometimes you need SPECIFICITY to make sure your styles are applied with strongest factor id Thanks for @Rob Fletcher for his great answer, in our company we have used

So please consider adding styles prefixed with the id of the app container

    #app input:focus::-webkit-input-placeholder, #app  textarea:focus::-webkit-input-placeholder {
        color: #FFFFFF;
    }

    #app input:focus:-moz-placeholder, #app textarea:focus:-moz-placeholder {
        color: #FFFFFF;
    }
Braggadocio answered 11/11, 2015 at 19:37 Comment(0)
B
5

With Pure CSS it worked for me. Make it transparent when Entered/Focues in input

 input:focus::-webkit-input-placeholder { /* Chrome/Opera/Safari */
    color: transparent !important;
 }
 input:focus::-moz-placeholder { /* Firefox 19+ */
   color: transparent !important;
 }
 input:focus:-ms-input-placeholder { /* IE 10+ */
   color: transparent !important;
 }
 input:focus:-moz-placeholder { /* Firefox 18- */
   color: transparent !important;
  }
Bromidic answered 2/12, 2018 at 21:47 Comment(0)
H
5

Angular any version

Just add this to your .css file

.hide_placeholder:focus::placeholder {
  color: transparent;
}

and use in your input in class

<input class="hide_placeholder"
Hellraiser answered 17/6, 2022 at 6:27 Comment(0)
D
4

To further refine Wallace Sidhrée's code sample:

$(function()
{  
      $('input').focusin(function()
      {
        input = $(this);
        input.data('place-holder-text', input.attr('placeholder'))
        input.attr('placeholder', '');
      });

      $('input').focusout(function()
      {
          input = $(this);
          input.attr('placeholder', input.data('place-holder-text'));
      });
})

This ensures that each input stores the correct placeholder text in the data attribute.

See a working example here in jsFiddle.

Delaunay answered 11/1, 2013 at 17:18 Comment(0)
Q
4

I like the css approach spiced with transitions. On Focus the placeholder fades out ;) Works also for textareas.

Thanks @Casey Chu for the great idea.

textarea::-webkit-input-placeholder, input::-webkit-input-placeholder { 
    color: #fff;
    opacity: 0.4;
    transition: opacity 0.5s;
    -webkit-transition: opacity 0.5s; 
}

textarea:focus::-webkit-input-placeholder, input:focus::-webkit-input-placeholder  { 
    opacity: 0;
}
Quarta answered 28/4, 2013 at 18:51 Comment(0)
E
4

For a pure CSS based solution:

input:focus::-webkit-input-placeholder  {color:transparent;}
input:focus::-moz-placeholder   {color:transparent;}
input:-moz-placeholder   {color:transparent;}

Note: Not yet supported by all browser vendors.

Reference: Hide placeholder text on focus with CSS by Ilia Raiskin.

Erst answered 14/2, 2014 at 20:13 Comment(0)
S
4

Using SCSS along with http://bourbon.io/, this solution is simple, elegant, and works on all web browsers:

input:focus {
  @include placeholder() {
    color: transparent;
  }
}

Use Bourbon ! It's good for you !

Simon answered 15/6, 2015 at 15:44 Comment(0)
B
3

HTML:

<input type="text" name="name" placeholder="enter your text" id="myInput" />

jQuery:

$('#myInput').focus(function(){
  $(this).attr('placeholder','');
});
$('#myInput').focusout(function(){
  $(this).attr('placeholder','enter your text');
});
Bushy answered 14/3, 2012 at 17:46 Comment(1)
This only assumes one input.Castlereagh
W
3

This piece of CSS worked for me:

input:focus::-webkit-input-placeholder {
        color:transparent;

}
Women answered 27/9, 2013 at 0:14 Comment(1)
That's A nice way of doing it without JQuery :)Jacquejacquelin
E
3

2018 > JQUERY v.3.3 SOLUTION: Working globaly for all input, textarea with placeholder.

 $(function(){
     $('input, textarea').on('focus', function(){
        if($(this).attr('placeholder')){
           window.oldph = $(this).attr('placeholder');
            $(this).attr('placeholder', ' ');
        };
     });

     $('input, textarea').on('blur', function(){
       if($(this).attr('placeholder')){
            $(this).attr('placeholder', window.oldph);
         };
     }); 
});
Erethism answered 31/5, 2018 at 8:59 Comment(0)
H
3

If your input background color is white, then you can set the placeholder text color on focus to match the input background - making the text invisible; theoretically. If you're input is a different color, then just simply change the color to match it.

input:focus::placeholder {
  color: white;
}

Also, you can set the color to "transparent" shown in other answers.

Heredity answered 31/5, 2021 at 5:0 Comment(0)
I
1

Demo is here: jsfiddle

Try this :

//auto-hide-placeholder-text-upon-focus
if(!$.browser.webkit){
$("input").each(
        function(){
            $(this).data('holder',$(this).attr('placeholder'));
            $(this).focusin(function(){
                $(this).attr('placeholder','');
            });
            $(this).focusout(function(){
                $(this).attr('placeholder',$(this).data('holder'));
            });

        });

}
Irtysh answered 29/8, 2012 at 6:11 Comment(2)
use $("input[placeholder]") instead to only select fields that have a placeholder attribute.Riddance
This is the best answer, simple, and deselects the others when out of focusCaucasia
P
1

for input

input:focus::-webkit-input-placeholder { color:transparent; }
input:focus:-moz-placeholder { color:transparent; }

for textarea

textarea:focus::-webkit-input-placeholder { color:transparent; }
textarea:focus:-moz-placeholder { color:transparent; }
Packard answered 20/5, 2014 at 5:9 Comment(0)
S
1
$("input[placeholder]").focusin(function () {
    $(this).data('place-holder-text', $(this).attr('placeholder')).attr('placeholder', '');
})
.focusout(function () {
    $(this).attr('placeholder', $(this).data('place-holder-text'));
});
Supersedure answered 15/9, 2014 at 22:17 Comment(0)
O
1
$("input[placeholder]").each(function () {
    $(this).attr("data-placeholder", this.placeholder);

    $(this).bind("focus", function () {
        this.placeholder = '';
    });
    $(this).bind("blur", function () {
        this.placeholder = $(this).attr("data-placeholder");
    });
});
Orphrey answered 28/2, 2015 at 9:53 Comment(0)
C
1

Besides all of above,I have two ideas.

You can add an element that imitates the palceholder.Then using javascript control the element showing and hiding.

But it is so complex,the other one is using the brother's selector of css.Just like this:

.placeholder { position: absolute; font-size: 14px; left: 40px; top: 11px; line-height: 1; pointer-events: none; }
.send-message input:focus + .placeholder { display: none; } 

23333,I have a poor English.Hope solve your problem.

Complement answered 27/5, 2016 at 3:30 Comment(1)
Please check this URL it will be useful to lift your content quality up ;Gyratory
P
1

No need to use any CSS or JQuery. You can do it right from the HTML input tag.

For example, In below email box, the placeholder text will disappear after clicking inside and the text will appear again if clicked outside.

<input type="email" placeholder="Type your email here..." onfocus="this.placeholder=''" onblur="this.placeholder='Type your email here...'">
Parotic answered 18/1, 2019 at 3:10 Comment(0)
B
0

try this function:

+It Hides The PlaceHolder On Focus And Returns It Back On Blur

+This function depends on the placeholder selector, first it selects the elements with the placeholder attribute, triggers a function on focusing and another one on blurring.

on focus : it adds an attribute "data-text" to the element which gets its value from the placeholder attribute then it removes the value of the placeholder attribute.

on blur : it returns back the placeholder value and removes it from the data-text attribute

<input type="text" placeholder="Username" />
$('[placeholder]').focus(function() {
    $(this).attr('data-text', $(this).attr('placeholder'));
    $(this).attr('placeholder', '');
  }).blur(function() {
      $(this).attr('placeholder', $(this).attr('data-text'));
      $(this).attr('data-text', '');
  });
});

you can follow me very well if you look what's happening behind the scenes by inspecting the input element

Barris answered 23/12, 2016 at 16:44 Comment(0)
X
0

The same thing i have applied in angular 5.

i created a new string for storing placeholder

newPlaceholder:string;

then i have used focus and blur functions on input box(i am using prime ng autocomplete).

Above placeholder is being set from typescript

Two functions i am using -

/* Event fired on focus to textbox*/
Focus(data) {
    this.newPlaceholder = data.target.placeholder;
    this.placeholder = '';
}
/* Event fired on mouse out*/
Blur(data) {
    this.placeholder = this.newPlaceholder;
}
Xyloid answered 12/3, 2018 at 5:15 Comment(0)
S
-1
/* Webkit */
[placeholder]:focus::-webkit-input-placeholder { opacity: 0; }
/* Firefox < 19 */
[placeholder]:focus:-moz-placeholder { opacity: 0; }
/* Firefox > 19 */
[placeholder]:focus::-moz-placeholder { opacity: 0; }
/* Internet Explorer 10 */
[placeholder]:focus:-ms-input-placeholder { opacity: 0; }
Slowly answered 3/12, 2017 at 2:21 Comment(1)
This answer is identical to a previous answer. If you have something to add or improve, please suggest an edit to the original answer.Leverhulme

© 2022 - 2024 — McMap. All rights reserved.