Rich
Rich

Reputation: 1156

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.

Upvotes: 7

Views: 14835

Answers (3)

Benjamin
Benjamin

Reputation: 568

You can use custom attributes "data", to swap content:

<input type="text" placeholder="Join our mailing list!" data-focus-placeholder="enter your email address..." class="focus-placeholder">​

Then, you need a JavaScript function to swap attributes on focus and focusout

jQuery('.focus-placeholder').on('focus focusout',function(){

    focusPlaceholder    = jQuery(this).attr('data-focus-placeholder');
    placeholder         = jQuery(this).attr('placeholder');

    jQuery(this).attr('placeholder', focusPlaceholder);
    jQuery(this).attr('data-focus-placeholder', placeholder);
});

More bout DATA attributes: https://www.w3schools.com/tags/att_global_data.asp

Upvotes: 0

No Results Found
No Results Found

Reputation: 102745

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.

Upvotes: 2

Ram
Ram

Reputation: 144669

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

http://jsfiddle.net/ByLGs/

Upvotes: 21

Related Questions