Question

I made this simple function to add placeholder in browsers that do not support it:

DEMO

The question is: How can I add to that function the possibility to remove the placeholder when the user click inside it?

Was it helpful?

Solution

Try to use removeAttr() like,

$('input,textarea').focus(function(){
   $(this).removeAttr('placeholder');
});

Demo

To get the placeholder value again on blur() try this,

$('input,textarea').focus(function(){
   $(this).data('placeholder',$(this).attr('placeholder'))
          .attr('placeholder','');
}).blur(function(){
   $(this).attr('placeholder',$(this).data('placeholder'));
});

Demo 1

OTHER TIPS

There is no need to use javascript function to accomplish this, a simpler solution is:

<input type="text" placeholder="enter your text" onfocus="this.placeholder=''" onblur="this.placeholder='enter your text'" />

CSS worked for me:

input:focus::-webkit-input-placeholder {
    color: transparent;
}
$("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");
    });
});

A very simple and comprehensive solution for this is which works in Mozila, IE, Chrome, Opera and Safari:

<input type="text" placeholder="your placeholder" onfocus="this.placeholder=''" onblur="this.placeholder='your placeholder'" />
 $('*').focus(function(){
  $(this).attr("placeholder",'');
  });

Try This hope it helps

$('input,textarea').focus(function()
{
$(this).attr('placeholder','');

});
$('input').focus(function()
{
  $(this).attr('placeholder','');

});

For browsers that don't support placeholder you can use this: https://github.com/mathiasbynens/jquery-placeholder. Add the placeholder attribute normally as for HTML5, then call this plugin: $('[placeholder]').placeholder();. Then use Rohan Kumar's code and will be cross-browser.

This is my solution on click not on focus:

$(document).on('click','input',function(){
    var $this = $(this);
    var place_val = $this.attr('placeholder');
    if(place_val != ''){
        $this.data('placeholder',place_val).removeAttr('placeholder');
    }
}).on('blur','input',function(){
    var $this = $(this);
    var place_val = $this.data('placeholder');
    if(place_val != ''){
        $this.attr('placeholder',place_val);
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top