Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle through placeholder text in form with JQuery?

Tags:

jquery

I'm fairly new to JQuery, so I wasn't sure where to start on this problem.

I have a form on a website that I want to show various placeholders temporarily and cycle through them (to imitate a number of options the user could input there; like Alice, Bob, Charles, etc. for a NAME form input) before the user clicks to input their own text.

I found this example – http://jsfiddle.net/eFjnU/ (code below) – that cycles through text, but how could I apply that to the temporary placeholders in a form input area?

HTML

<div id="content-1">Sample text 1</div>
<div id="content-2">Sample text 2</div>
<div id="content-3">Sample text 3</div>
<div id="content-4">Sample text 4</div>
<div id="content-5">Sample text 5</div>
<div id="content-6">Sample text 6</div>
<div id="content-7">Sample text 7</div>

JQuery

var divs = $('div[id^="content-"]').hide(),
    i = 0;

(function cycle() { 

    divs.eq(i).fadeIn(400)
              .delay(1000)
              .fadeOut(400, cycle);

    i = ++i % divs.length;

})();

You can change the above from div to input, but that will cycle the entire input box in and out, and I want only the placeholder text to fade in/out.

EDIT 1:

For example:

<input type="text" name="whatever" type="text" placeholder="Alice">
<input type="text" name="whatever" type="text" placeholder="Bob">
<input type="text" name="whatever" type="text" placeholder="Charles">
like image 297
alxlvt Avatar asked Oct 04 '22 03:10

alxlvt


1 Answers

You can't animate placeholder text but you can create a function that changes the attribute periodically:

Demo fiddle

var placeholders = ['Alice','Bob','Charles'];

(function cycle() { 
    var placeholder = placeholders.shift();
    $('input').attr('placeholder',placeholder);
    placeholders.push(placeholder);
    setTimeout(cycle,1000);
})();

That's basically what you want minus the fadeIn/fadeOut

like image 186
omma2289 Avatar answered Oct 07 '22 19:10

omma2289