Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Placeholder Text On Focus

Is there a simple solution for changing placeholder text when an input is in focus? For example:

<input type="text" placeholder="Join our mailing list!">

would become this:

<input type="text" placeholder="enter your email address...">

while the input is active.

like image 316
Rich Avatar asked Sep 21 '12 17:09

Rich


People also ask

How do I change placeholder text in focus?

$('input'). focus(function() { $(this). attr('placeholder', 'enter your email address...') }).

How do I change the placeholder text?

The “placeholder” property is used to get or set the placeholder of an input text. This can be used to change the placeholder text to a new one. The element is first selected using a jQuery selector. The new placeholder text can then be assigned to the element's placeholder property.

How do I change placeholder text in CSS?

Change Input Placeholder Text with CSS You can use the ::placeholder pseudo-element to change the styles of the placeholder text, which includes the ability to change the background.

Can you style placeholder text?

The ::placeholder selector selects form elements with placeholder text, and let you style the placeholder text. The placeholder text is set with the placeholder attribute, which specifies a hint that describes the expected value of an input field.


2 Answers

$('input').focus(function() {
    $(this).attr('placeholder', 'enter your email address...')
}).blur(function() {
    $(this).attr('placeholder', 'Join our mailing list!')
})

http://jsfiddle.net/ByLGs/

  • attr
  • focus
  • blur
like image 168
undefined Avatar answered Oct 18 '22 21:10

undefined


You have this tagged "jQuery" so I assume you're open to using it. Here's a simple way:

<input type="text" placeholder="Join our mailing list!" title="enter your email address...">​
$('input').on('focus', function(){
    $(this).data('placeholder', $(this).attr('placeholder')); // Store for blur
    $(this).attr('placeholder', $(this).attr('title'));
}).on('blur', function(){
    $(this).attr('placeholder', $(this).data('placeholder'));
});​

Demo: http://jsfiddle.net/m6j8m/

This could be shortened up, but you get the idea. This way you don't have to keep track of attribute values in your javascript, it's all in the HTML so it's a one-size-fits-all solution. If using title doesn't suit your needs, you can use data- attributes instead or some other attribute.

like image 32
Wesley Murch Avatar answered Oct 18 '22 19:10

Wesley Murch