简体   繁体   中英

How does one target a placeholder value in a textarea tag using pure javascript

I currently have a div named comp

<div id="comp"></div>

Using Javascript, I have added a textarea tag with a placeholder value

var comp = document.getElementById('comp');
setTimeout(function(){
        comp.innerHTML = '<textarea placeholder="Write on me now, or else... you will have to watch me write on"></textarea>';
    }, 1500); 

Keep in mind that it has taken about 1.5 seconds to write out the entire text word by word.

How does one append the words "and on" every 200 milliseconds using setInterval to the placeholder value in textarea, so that every .2 seconds "and on" keeps getting written until the user writes something.

Feel free to take a look at this JSFiddle to clarify. (aesthetics are a bit messed up, but it get's the job done). Thanks and I really appreciate it!

Also, I have tried to find similar questions and I haven't been able to find any. It would really help if someone would direct me towards them.

Although I don't quite understand what you want, here's what I think you want:

 var textarea = document.getElementById('test'); setInterval(function () { textarea.placeholder += ' and on'; }, 1500); 
 <div id="comp"><textarea id='test' placeholder="Write on me now, or else... you will have to watch me write on"></textarea></div> 

Every 1.5 seconds, and on is added to the placeholder of the textarea with the id test

You can get a reference to the textarea using getElementsByTagName , then start an interval that adds text to the placeholder. When the user starts typing you might want to stop the interval:

 setTimeout(function(){ var comp = document.getElementById('comp'); comp.innerHTML = '<textarea placeholder="Write on me now, or else... you will have to watch me write on"></textarea>'; var tex = comp.getElementsByTagName('textarea')[0]; var handle = window.setInterval(function(){ if (tex.value.length == 0) { tex.placeholder += ' and on'; } else { window.clearInterval(handle); } }, 200); }, 1500); 
 textarea { width: 90%; height: 200px; } 
 <div id="comp"></div> 

Also, you might want to add a counter (or just check the length of the placeholder), so that you can stop the interval after a certain number of times. If you leave the interval on indefinitely, the browser will eventually crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM