[jquery] How do I auto-hide placeholder text upon focus using css or jquery?

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?

Kind regards.

This question is related to jquery css html google-chrome placeholder

The answer is


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.


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'));
            });

        });

}

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;
}

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

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


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/


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.


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...'">

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; }

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'));
        });
    });
};

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);
         };
     }); 
});

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:

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

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


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.

_x000D_
_x000D_
::-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 */
_x000D_
<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>
_x000D_
_x000D_
_x000D_

Revisions

  • Edit 1 (2017): Updated to support modern browsers.
  • Edit 2 (2020): Added the runnable Stack Snippet.

/* 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; }

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; }

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

input:focus::-webkit-input-placeholder {
    opacity: 0;
}

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.


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');
});

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


Edit: All browsers support now

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

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+ */

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

$("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");
    });
});

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;
}

This piece of CSS worked for me:

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

}

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 !


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;
  }

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to google-chrome

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Examples related to placeholder

Keep placeholder text in UITextField on input in IOS HTML Input - already filled in text Add placeholder text inside UITextView in Swift? Bootstrap select dropdown list placeholder fail to change placeholder color with Bootstrap 3 Not showing placeholder for input type="date" field Use Font Awesome Icon in Placeholder How do I put hint in a asp:textbox How to support placeholder attribute in IE8 and 9 HTML5 image icon to input placeholder